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
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
SQL Commands | DDL, DQL, DML, DCL and TCL Commands SQL commands are crucial for managing databases effectively. These commands are divided into categories such as Data Definition Language (DDL), Data Manipulation Language (DML), Data Control Language (DCL), Data Query Language (DQL), and Transaction Control Language (TCL). In this article, we will e
7 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Dijkstra's Algorithm to find Shortest Paths from a Source to all Given a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph contains V vertices, numbered from 0 to V - 1.Note: The given graph does not contain any negative edge. Example
12 min read