Iterative program to count leaf nodes in a Binary Tree
Last Updated :
26 Sep, 2024
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: 3
Explanation: Three leaf nodes are 3, 4 and 5 as both of their left and right child is NULL.
Input:

Output: 3
Explanation: Three leaf nodes are 4, 6 and 7 as both of their left and right child is NULL.
Approach:
The idea is to use level order traversal. During traversal, if we find a node whose left and right children are NULL, we increment count.
Follow the steps below to solve the problem:
- 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.
- Repeat the process until all nodes have been processed (i.e., the queue is empty).
- Finally, return the count of leaf nodes found during the traversal.
Below is the implementation of the above approach:
C++
// C++ code to count leaf nodes in a binary tree
// using level order traversal
#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;
}
// Initialize a queue for level order traversal
queue<Node*> q;
q.push(root);
int count = 0;
// Traverse the tree using level order traversal
while (!q.empty()) {
Node* curr = q.front();
q.pop();
// Check if the current node is a leaf node
if (curr->left == nullptr && curr->right == nullptr) {
count++;
}
// Enqueue left and right children if they exist
if (curr->left != nullptr) {
q.push(curr->left);
}
if (curr->right != nullptr) {
q.push(curr->right);
}
}
return count;
}
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;
}
Java
// Java code to count leaf nodes in a binary tree
// using level order traversal
import java.util.LinkedList;
import java.util.Queue;
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;
}
// Initialize a queue for level order traversal
Queue<Node> queue = new LinkedList<>();
queue.add(root);
int count = 0;
// Traverse the tree using level order traversal
while (!queue.isEmpty()) {
Node curr = queue.poll();
// Check if the current node is a leaf node
if (curr.left == null && curr.right == null) {
count++;
}
// Enqueue left and right children if they exist
if (curr.left != null) {
queue.add(curr.left);
}
if (curr.right != null) {
queue.add(curr.right);
}
}
return count;
}
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 level order traversal
from collections import deque
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
# Initialize a queue for level order traversal
queue = deque([root])
count = 0
# Traverse the tree using level order traversal
while queue:
curr = queue.popleft()
# Check if the current node is a leaf node
if curr.left is None and curr.right is None:
count += 1
# Enqueue left and right children if they exist
if curr.left is not None:
queue.append(curr.left)
if curr.right is not None:
queue.append(curr.right)
return count
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 level order traversal
using System;
using System.Collections.Generic;
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;
}
// Initialize a queue for level order traversal
Queue<Node> queue = new Queue<Node>();
queue.Enqueue(root);
// Variable to count leaf nodes
int count = 0;
// Traverse the tree using level order traversal
while (queue.Count > 0) {
Node curr = queue.Dequeue();
// Check if the current node is a leaf node
if (curr.left == null && curr.right == null) {
count++;
}
// Enqueue left and right children if they exist
if (curr.left != null) {
queue.Enqueue(curr.left);
}
if (curr.right != null) {
queue.Enqueue(curr.right);
}
}
return count;
}
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 level order traversal
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;
}
// Initialize a queue for level order traversal
const queue = [];
queue.push(root);
let count = 0;
// Traverse the tree using level order traversal
while (queue.length > 0) {
const curr = queue.shift();
// Check if the current node is a leaf node
if (curr.left === null && curr.right === null) {
count++;
}
// Enqueue left and right children if they exist
if (curr.left !== null) {
queue.push(curr.left);
}
if (curr.right !== null) {
queue.push(curr.right);
}
}
return count;
}
// 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));
Time Complexity: O(n), where n is the number of nodes in the tree, since each node is visited exactly once.
Auxiliary space: O(n), space used for queue.
Related article:
Similar Reads
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 a
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
Count half nodes in a Binary tree (Iterative and Recursive) Given A binary Tree, how do you count all the half nodes (which has only one child) without using recursion? Note leaves should not be touched as they have both children as NULL. Input : Root of below treeOutput : 3 Nodes 7, 5 and 9 are half nodes as one of their child is Null. So count of half node
12 min read
Count full nodes in a Binary tree (Iterative and Recursive) Given A binary Tree, how do you count all the full nodes (Nodes which have both children as not NULL) without using recursion and with recursion? Note leaves should not be touched as they have both children as NULL. Nodes 2 and 6 are full nodes has both child's. So count of full nodes in the above t
12 min read
Deepest right leaf node in a binary tree | Iterative approach Given a Binary Tree, find the deepest leaf node that is the right child of its parent. For example, consider the following tree. The deepest right leaf node is the node with the value 10. Examples: Input : 1 / \ 2 3 \ / \ 4 5 6 \ \ 7 8 / \ 9 10 Output : 10 The idea is similar to Method 2 of level or
7 min read
Count root to leaf paths having exactly K distinct nodes in a Binary Tree Given a Binary Tree consisting of N nodes rooted at 1, an integer K and an array arr[] consisting of values assigned to each node, the task is to count the number of root to leaf paths having exactly K distinct nodes in the given Binary Tree. Examples: Input: N = 3, Edges[][] = {{1, 2}, {1, 3}}, arr
11 min read
Iterative program to Calculate Size of a tree Given a binary tree, the task is to find the size of the tree. The size of a tree is the number of nodes present in the tree.Example:Input: Output: 6Explanation: The number of nodes in the above binary tree is 6.Approach:The idea is to use Level Order Traversal to find the size of the tree. Initiali
5 min read
Count of nodes in a binary tree having their nodes in range [L, R] Given a Binary Tree consisting of n nodes and two positive integers l and r, the task is to find the count of nodes having their value in the range [l, r].Examples:Input: l = 4, r = 15Output: 4Explanation: The nodes in the given Tree that lies in the range [4, 15] are {4, 5, 6, 7}.Input: l = 1, r =
10 min read
Deepest left leaf node in a binary tree | iterative approach Given a Binary Tree, find the deepest leaf node that is left child of its parent. For example, consider the following tree. The deepest left leaf node is the node with value 9. Examples: Input : 1 / \ 2 3 / / \ 4 5 6 \ \ 7 8 / \ 9 10 Output : 9 Recursive approach to this problem is discussed hereFor
8 min read
Count of exponential paths in a Binary Tree Given a Binary Tree, the task is to count the number of Exponential paths in the given Binary Tree. Exponential Path is a path where root to leaf path contains all nodes being equal to xy, & where x is a minimum possible positive constant & y is a variable positive integer. Example: Input: 2
11 min read