VOOZH about

URL: https://www.geeksforgeeks.org/dsa/write-a-c-program-to-get-count-of-leaf-nodes-in-a-binary-tree/

⇱ Count Leaf Nodes in a Binary Tree - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Count Leaf Nodes in a Binary Tree

Last Updated : 10 May, 2026

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.

Using Recursion - O(n) Time and O(h) Space

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

  • 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.

Output
3

Iterative Approach - O(n) Time and O(n) Space

The idea is to use the queue based level order traversal to efficiently count the leaf nodes in a binary tree. We check 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.

  • Create a queue to traverse in level order manner and a variable count to keep track of the number of leaf nodes. Start by enqueuing the root node.
  • While the queue is not empty, proceed with the traversal.
    • Dequeue the front node from the queue and check its children.
    • If both the left and right children of the current node are NULL, increment the count variable by 1, indicating that a leaf node has been found.
    • If the current node has a left child, enqueue it into the queue. Similarly, if it has a right child, enqueue that child also.
  • Finally, return the count of leaf nodes found during the traversal.

Output
3
Comment
Article Tags:
Article Tags: