Iterative program to count leaf nodes in a Binary Tree

Given a binary tree, count leaves in the tree without using recursion. A node is a leaf node if both left and right children of it are NULL.
 

  Example Tree  

 
Leaves count for the above tree is 3.

 

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. 
 

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to count leaf nodes in a Binary Tree
#include <bits/stdc++.h>
using namespace std;
  
/* A binary tree Node has data, pointer to left
   child  and a pointer to right child */
struct Node
{
    int data;
    struct Node* left, *right;
};
  
/* Function to get the count of leaf Nodes in
   a binary tree*/
unsigned int getLeafCount(struct Node* node)
{
    // If tree is empty
    if (!node)
        return 0;
  
    // Initialize empty queue.
    queue<Node *> q;
  
    // Do level order traversal starting from root
    int count = 0; // Initialize count of leaves
    q.push(node);
    while (!q.empty())
    {
        struct Node *temp = q.front();
        q.pop();
  
        if (temp->left != NULL)
            q.push(temp->left);
        if (temp->right != NULL)
            q.push(temp->right);
        if (temp->left == NULL && temp->right == NULL)
            count++;
    }
    return count;
}
  
/* Helper function that allocates a new Node with the
   given data and NULL left and right pointers. */
struct Node* newNode(int data)
{
    struct Node* node = new Node;
    node->data = data;
    node->left = node->right = NULL;
    return (node);
}
  
/* Driver program to test above functions*/
int main()
{
    /*   1
        /  \
      2     3
     / \
    4   5
    Let us create Binary Tree shown in 
    above example */
  
    struct Node *root = newNode(1);
    root->left        = newNode(2);
    root->right       = newNode(3);
    root->left->left  = newNode(4);
    root->left->right = newNode(5);
  
    /* get leaf count of the above created tree */
    cout << getLeafCount(root);
  
    return 0;
}
chevron_right

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to count leaf nodes
// in a Binary Tree
import java.util.*;
  
class GFG 
{
    /* A binary tree Node has data, 
    pointer to left child and
    a pointer to right child */
    static class Node 
    {
        int data;
        Node left, right;
    }
  
    /* Function to get the count of 
    leaf Nodes in a binary tree*/
    static int getLeafCount(Node node)
    {
        // If tree is empty
        if (node == null)
        {
            return 0;
        }
  
        // Initialize empty queue.
        Queue<Node> q = new LinkedList<>();
  
        // Do level order traversal starting from root
        int count = 0; // Initialize count of leaves
        q.add(node);
        while (!q.isEmpty()) 
        {
            Node temp = q.peek();
            q.poll();
  
            if (temp.left != null
            {
                q.add(temp.left);
            }
            if (temp.right != null)
            {
                q.add(temp.right);
            }
            if (temp.left == null && 
                temp.right == null
            {
                count++;
            }
        }
        return count;
    }
  
    /* Helper function that allocates 
    a new Node with the given data 
    and null left and right pointers. */
    static Node newNode(int data)
    {
        Node node = new Node();
        node.data = data;
        node.left = node.right = null;
        return (node);
    }
  
    // Driver Code
    public static void main(String[] args) 
    {
        {
            /*   1
                / \
               2   3
              / \
             4   5
            Let us create Binary Tree shown in 
            above example */
            Node root = newNode(1);
            root.left = newNode(2);
            root.right = newNode(3);
            root.left.left = newNode(4);
            root.left.right = newNode(5);
  
            /* get leaf count of the above created tree */
            System.out.println(getLeafCount(root));
        }
    }
}
  
// This code is contributed by Rajput-Ji
chevron_right

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to count leaf nodes 
# in a Binary Tree 
from queue import Queue 
  
# Helper function that allocates a new 
# Node with the given data and None 
# left and right pointers. 
class newNode:
    def __init__(self, data):
        self.data = data 
        self.left = self.right = None
          
# Function to get the count of leaf 
# Nodes in a binary tree
def getLeafCount(node):
      
    # If tree is empty 
    if (not node):
        return 0
  
    # Initialize empty queue. 
    q = Queue()
  
    # Do level order traversal 
    # starting from root 
    count = 0 # Initialize count of leaves 
    q.put(node) 
    while (not q.empty()):
        temp = q.queue[0
        q.get()
  
        if (temp.left != None):
            q.put(temp.left) 
        if (temp.right != None):
            q.put(temp.right) 
        if (temp.left == None and
            temp.right == None): 
            count += 1
    return count
  
# Driver Code
if __name__ == '__main__':
      
    # 1 
    # / \ 
    # 2 3 
    # / \ 
    # 4 5 
    # Let us create Binary Tree shown 
    # in above example 
    root = newNode(1
    root.left = newNode(2
    root.right = newNode(3
    root.left.left = newNode(4
    root.left.right = newNode(5
  
    # get leaf count of the above 
    # created tree 
    print(getLeafCount(root))
  
# This code is contributed by PranchalK
chevron_right

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to count leaf nodes
// in a Binary Tree
using System;
using System.Collections.Generic; 
      
class GFG 
{
    /* A binary tree Node has data, 
    pointer to left child and
    a pointer to right child */
    public class Node 
    {
        public int data;
        public Node left, right;
    }
  
    /* Function to get the count of 
    leaf Nodes in a binary tree*/
    static int getLeafCount(Node node)
    {
        // If tree is empty
        if (node == null)
        {
            return 0;
        }
  
        // Initialize empty queue.
        Queue<Node> q = new Queue<Node>();
  
        // Do level order traversal starting from root
        int count = 0; // Initialize count of leaves
        q.Enqueue(node);
        while (q.Count!=0) 
        {
            Node temp = q.Peek();
            q.Dequeue();
  
            if (temp.left != null
            {
                q.Enqueue(temp.left);
            }
            if (temp.right != null)
            {
                q.Enqueue(temp.right);
            }
            if (temp.left == null && 
                temp.right == null
            {
                count++;
            }
        }
        return count;
    }
  
    /* Helper function that allocates 
    a new Node with the given data 
    and null left and right pointers. */
    static Node newNode(int data)
    {
        Node node = new Node();
        node.data = data;
        node.left = node.right = null;
        return (node);
    }
  
    // Driver Code
    public static void Main(String[] args) 
    {
        {
            /* 1
                / \
            2 3
            / \
            4 5
            Let us create Binary Tree shown in 
            above example */
            Node root = newNode(1);
            root.left = newNode(2);
            root.right = newNode(3);
            root.left.left = newNode(4);
            root.left.right = newNode(5);
  
            /* get leaf count of the above created tree */
            Console.WriteLine(getLeafCount(root));
        }
    }
}
  
// This code is contributed by 29AjayKumar
chevron_right

Output

3

Output: 
 

 3


Time Complexity: O(n)

Here is a recursive solution for the same problem:

The idea is simple we brake the larger tree into smaller sub-trees and solve for them to get the final answer.

Below is the implementation of the above approach.

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java Program for above approach
import java.util.LinkedList;
import java.util.Queue;
import java.io.*;
import java.util.*;
  
class GfG 
{
    
  // Node class
  static class Node 
  {
    int data;
    Node left, right;
  }
  
  // Program to count leaves
  static int countLeaves(Node node)
  {
  
    // If the node itself is "null" 
    // return 0, as there
    // are no leaves
    if (node == null)
      return 0;
  
    // It the node is a leaf then 
    // both right and left
    // children will be "null"
    if (node.left == null && 
                node.right == null)
      return 1;
  
    // Now we count the leaves in 
    // the left and right
    // subtrees and return the sum
    return countLeaves(node.left)
             + countLeaves(node.right);
  }
   
  // Class newNode of Node type
  static Node newNode(int data)
  {
    Node node = new Node();
    node.data = data;
    node.left = node.right = null;
    return (node);
  }
  
  // Driver Code
  public static void main(String[] args)
  {
     
      Node root = newNode(1);
      root.left = newNode(2);
      root.right = newNode(3);
      root.left.left = newNode(4);
      root.left.right = newNode(5);
  
      /* get leaf count of the above 
      created tree */
      System.out.println(countLeaves(root));
  }
}
//Code by Rounik Prashar
chevron_right

Output
3

This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
 

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.





Article Tags :
Practice Tags :