Open In App

Iterative program to count leaf nodes in a Binary Tree

Last Updated : 26 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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.

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));

Output
3

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:



Next Article
Article Tags :
Practice Tags :

Similar Reads