Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on Tree
  • Practice Tree
  • MCQs on Tree
  • Tutorial on Tree
  • Types of Trees
  • Basic operations
  • Tree Traversal
  • Binary Tree
  • Complete Binary Tree
  • Ternary Tree
  • Binary Search Tree
  • Red-Black Tree
  • AVL Tree
  • Full Binary Tree
  • B-Tree
  • Advantages & Disadvantages
Open In App
Next Article:
Pairwise Swap leaf nodes in a binary tree
Next article icon

Program to count leaf nodes in a binary tree

Last Updated : 26 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

Given a Binary Tree, the task is to count leaves in it. A node is a leaf node if both left and right child nodes of it are NULL. 

Example:

Input:

ex-3

Output: 3
Explanation: Three leaf nodes are 3, 4 and 5 as both of their left and right child is NULL.

Input:

ex-4

Output: 3
Explanation: Three leaf nodes are 4, 6 and 7 as both of their left and right child is NULL.

Table of Content

  • [Expected Approach - 1] Using Recursion - O(n) Time and O(n) Space
  • [Expected Approach - 2] Iterative Approach - O(n) Time and O(n) Space

[Expected Approach - 1] Using Recursion - O(n) Time and O(n) Space

The idea is to determine the count of leaf nodes in a binary tree using a recursive approach. If a node is NULL, the function returns 0. If both the left and right child nodes of the current node are NULL, it returns 1, indicating a leaf node. The count of leaf nodes from the left and right subtrees provide the total count leaf nodes.

  • Leaf count of a tree = Leaf count of left subtree + Leaf count of right subtree

Follow the steps below to solve the problem:

  • Create a function named countLeaves() of that takes node as an input parameter and return the count of leaf nodes.
  • Set the conditions:
    • If the node is NULL, return 0.
    • If the node has no left or right child, return 1.
    • Recursively call countLeaves() on the left and right child nodes if the node has left or right children, and then return the total of the results.

Below is the implementation of the above approach:

C++
// C++ code to count leaf nodes in a binary tree // using recursion #include <bits/stdc++.h> using namespace std;  struct Node {     int data;     Node *left, *right;      Node(int val) {         data = val;         left = right = nullptr;     } };  // Function to count the leaf nodes in a binary tree int countLeaves(Node* root) {        // If the root is null, return 0     if (root == nullptr) {         return 0;     }          // If the node has no left or right child,     // it is a leaf node     if (root->left == nullptr && root->right == nullptr) {         return 1;     }          // Recursively count leaf nodes in left      // and right subtrees     return countLeaves(root->left) + countLeaves(root->right); }  int main() {        // Representation of input binary tree     //        1     //       / \     //      2   3     //     / \     //    4   5     Node* root = new Node(1);     root->left = new Node(2);     root->right = new Node(3);     root->left->left = new Node(4);     root->left->right = new Node(5);      cout << countLeaves(root) << "\n";        return 0; } 
C
// C code to count leaf nodes in a binary tree // using recursion #include <stdio.h> #include <stdlib.h>  struct Node {     int data;     struct Node *left, *right; };  // Function to count the leaf nodes in a binary tree int countLeaves(struct Node* root) {        // If root is NULL, return 0     if (root == NULL) {         return 0;     }          // If the node has no left or right child,      // it is a leaf     if (root->left == NULL && root->right == NULL) {         return 1;     }          // Recursively count the leaves in the left      // and right subtrees     return countLeaves(root->left)                       + countLeaves(root->right); }  struct Node* createNode(int val) {     struct Node* node        = (struct Node*)malloc(sizeof(struct Node));     node->data = val;     node->left = node->right = NULL;     return node; }  int main() {        // Representation of input binary tree     //        1     //       / \     //      2   3     //     / \     //    4   5     struct Node* root = createNode(1);     root->left = createNode(2);     root->right = createNode(3);     root->left->left = createNode(4);     root->left->right = createNode(5);      printf("%d\n", countLeaves(root));      return 0; } 
Java
// Java code to count leaf nodes in a binary tree // using recursion class Node {     int data;     Node left, right;      Node(int val) {         data = val;         left = right = null;     } }  class GfG {      // Function to count the leaf nodes in a binary tree     static int countLeaves(Node root) {                // If root is NULL, return 0         if (root == null) {             return 0;         }          // If the node has no left or right child,          // it is a leaf         if (root.left == null && root.right == null) {             return 1;         }          // Recursively count the leaves in the          // left and right subtrees         return countLeaves(root.left)                           + countLeaves(root.right);     }      public static void main(String[] args) {                // Representation of input binary tree         //        1         //       / \         //      2   3         //     / \         //    4   5         Node root = new Node(1);         root.left = new Node(2);         root.right = new Node(3);         root.left.left = new Node(4);         root.left.right = new Node(5);          System.out.println(countLeaves(root));     } } 
Python
# Python code to count leaf nodes in a binary tree # using recursion class Node:     def __init__(self, data):         self.data = data         self.left = None         self.right = None  def countLeaves(root):        # If root is None, return 0     if root is None:         return 0      # If the node has no left or right child, it is a leaf     if root.left is None and root.right is None:         return 1      # Recursively count the leaves in the left and right subtrees     return countLeaves(root.left) + countLeaves(root.right)  if __name__ == "__main__":        # Representation of input binary tree     #        1     #       / \     #      2   3     #     / \     #    4   5     root = Node(1)     root.left = Node(2)     root.right = Node(3)     root.left.left = Node(4)     root.left.right = Node(5)      print(countLeaves(root)) 
C#
// C# code to count leaf nodes in a binary tree // using recursion using System;  class Node {     public int data;     public Node left, right;      public Node(int val) {         data = val;         left = right = null;     } }  class GfG {      static int CountLeaves(Node root) {                // If the root is null, return 0         if (root == null) {             return 0;         }          // If the node has no left or right child,         // it is a leaf         if (root.left == null && root.right == null) {             return 1;         }          // Recursively count the leaves in the left          // and right subtrees         return CountLeaves(root.left)                               + CountLeaves(root.right);     }      static void Main(string[] args) {                // Representation of input binary tree         //        1         //       / \         //      2   3         //     / \         //    4   5         Node root = new Node(1);         root.left = new Node(2);         root.right = new Node(3);         root.left.left = new Node(4);         root.left.right = new Node(5);          Console.WriteLine(CountLeaves(root));     } } 
JavaScript
// JavaScript code to count leaf nodes in a binary tree // using recursion class Node {     constructor(data) {         this.data = data;         this.left = null;         this.right = null;     } }  function countLeaves(root) {      // If the root is null, return 0     if (root === null) {         return 0;     }      // If the node has no left or right child,     // it is a leaf     if (root.left === null && root.right === null) {         return 1;     }      // Recursively count the leaves in the left      // and right subtrees     return countLeaves(root.left) + countLeaves(root.right); }  // Representation of input binary tree //        1 //       / \ //      2   3 //     / \ //    4   5 let root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.left.left = new Node(4); root.left.right = new Node(5);  console.log(countLeaves(root)); 

Output
3 

Time Complexity: O(n), where n is the number of nodes in the binary tree, as each node is visited once to count the leaf nodes.
Space Complexity: O(h), where h is the height of the tree, due to the recursive call stack used for traversal.

[Expected Approach - 2] Iterative Approach - O(n) Time and O(n) Space

The idea is to use level order traversal to efficiently count the leaf nodes in a binary tree. By initializing a queue, we can traverse the tree level by level, checking each node as it is dequeued from queue. For every node, we check if it has no left or right children, indicating that it is a leaf node, and increment our count accordingly. Please refer to Iterative program to count leaf nodes in a Binary Tree for implementation.


Next Article
Pairwise Swap leaf nodes in a binary tree
author
kartik
Improve
Article Tags :
  • Tree
  • DSA
  • Ola Cabs
Practice Tags :
  • Ola Cabs
  • Tree

Similar Reads

  • Iterative program to count leaf nodes in a Binary Tree
    Given a Binary Tree, the task is to count leaves in it. A node is a leaf node if both left and right child nodes of it are NULL. Example: Input: Output: 3Explanation: Three leaf nodes are 3, 4 and 5 as both of their left and right child is NULL.Input: Output: 3Explanation: Three leaf nodes are 4, 6
    7 min read
  • Count Non-Leaf nodes in a Binary Tree
    Given a Binary tree, count the total number of non-leaf nodes in the tree Examples: Input : Output :2 Explanation In the above tree only two nodes 1 and 2 are non-leaf nodesRecommended PracticeCount Non-Leaf Nodes in TreeTry It! We recursively traverse the given tree. While traversing, we count non-
    10 min read
  • Closest leaf to a given node in Binary Tree
    Given a Binary Tree and a node x in it, find distance of the closest leaf to x in Binary Tree. If given node itself is a leaf, then distance is 0.Examples: Input: Root of below tree And x = pointer to node 13 10 / \ 12 13 / 14 Output 1 Distance 1. Closest leaf is 14. Input: Root of below tree And x
    12 min read
  • Pairwise Swap leaf nodes in a binary tree
    Given a binary tree, we need to write a program to swap leaf nodes in the given binary tree pairwise starting from left to right as shown below. Tree before swapping: Tree after swapping: The sequence of leaf nodes in original binary tree from left to right is (4, 6, 7, 9, 10). Now if we try to form
    11 min read
  • Count balanced nodes present in a binary tree
    Given a binary tree, the task is to count the number of balanced nodes in the given tree. Balanced nodes of a binary tree are defined as the nodes which contains both left and right subtrees with their respective sum of node values equal. Examples: Input: 9 / \ 2 4 / \ \ -1 3 0 Output: 1Explanation:
    7 min read
  • Count of root to leaf paths in a Binary Tree that form an AP
    Given a Binary Tree, the task is to count all paths from root to leaf which forms an Arithmetic Progression. Examples: Input: Output: 2 Explanation: The paths that form an AP in the given tree from root to leaf are: 1->3->5 (A.P. with common difference 2)1->6->11 (A.P. with common differ
    7 min read
  • Count of Fibonacci paths in a Binary tree
    Given a Binary Tree, the task is to count the number of Fibonacci paths in the given Binary Tree. Fibonacci Path is a path which contains all nodes in root to leaf path are terms of Fibonacci series. Example: Input: 0 / \ 1 1 / \ / \ 1 10 70 1 / \ 81 2 Output: 2 Explanation: There are 2 Fibonacci pa
    10 min read
  • Print Root-to-Leaf Paths in a Binary Tree
    Given a Binary Tree of nodes, the task is to find all the possible paths from the root node to all the leaf nodes of the binary tree. Example: Input: Output: 1 2 41 2 51 3 Using Recursion - O(n) Time and O(h) SpaceIn the recursive approach to print all paths from the root to leaf nodes, we can perfo
    2 min read
  • Count number of nodes in a complete Binary Tree
    Given the root of a Complete Binary Tree consisting of N nodes, the task is to find the total number of nodes in the given Binary Tree. Examples: Input: Output: 7 Input: Output: 5 Native Approach: The simple approach to solving the given tree is to perform the DFS Traversal on the given tree and cou
    15+ min read
  • Sum of all leaf nodes of binary tree
    Given a binary tree, find the sum of all the leaf nodes.Examples: Input : 1 / \ 2 3 / \ / \ 4 5 6 7 \ 8 Output : Sum = 4 + 5 + 8 + 7 = 24 Recommended PracticeSum of Leaf NodesTry It! The idea is to traverse the tree in any fashion and check if the node is the leaf node or not. If the node is the lea
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences