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.
C++
#include<iostream>usingnamespacestd;structNode{intdata;Node*left,*right;Node(intval){data=val;left=right=nullptr;}};// Function to count the leaf nodes in a binary treeintcountLeaves(Node*root){// If the root is null, return 0if(root==nullptr){return0;}// If the node has no left or right child,// it is a leaf nodeif(root->left==nullptr&&root->right==nullptr){return1;}// Recursively count leaf nodes in left // and right subtreesreturncountLeaves(root->left)+countLeaves(root->right);}intmain(){// Representation of input binary tree// 1// / \ // 2 3// / \ // 4 5Node*root=newNode(1);root->left=newNode(2);root->right=newNode(3);root->left->left=newNode(4);root->left->right=newNode(5);cout<<countLeaves(root)<<"\n";return0;}
Java
classNode{intdata;Nodeleft,right;Node(intval){data=val;left=right=null;}}classGfG{// Function to count the leaf nodes in a binary treestaticintcountLeaves(Noderoot){// If root is NULL, return 0if(root==null){return0;}// If the node has no left or right child, // it is a leafif(root.left==null&&root.right==null){return1;}// Recursively count the leaves in the // left and right subtreesreturncountLeaves(root.left)+countLeaves(root.right);}publicstaticvoidmain(String[]args){// Representation of input binary tree// 1// / \// 2 3// / \// 4 5Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);System.out.println(countLeaves(root));}}
Python
classNode:def__init__(self,data):self.data=dataself.left=Noneself.right=NonedefcountLeaves(root):# If root is None, return 0ifrootisNone:return0# If the node has no left or right child, it is a leafifroot.leftisNoneandroot.rightisNone:return1# Recursively count the leaves in the left and right subtreesreturncountLeaves(root.left)+countLeaves(root.right)if__name__=="__main__":# Representation of input binary tree# 1# / \# 2 3# / \# 4 5root=Node(1)root.left=Node(2)root.right=Node(3)root.left.left=Node(4)root.left.right=Node(5)print(countLeaves(root))
C#
usingSystem;classNode{publicintdata;publicNodeleft,right;publicNode(intval){data=val;left=right=null;}}classGfG{staticintcountLeaves(Noderoot){// If the root is null, return 0if(root==null){return0;}// If the node has no left or right child,// it is a leafif(root.left==null&&root.right==null){return1;}// Recursively count the leaves in the left // and right subtreesreturncountLeaves(root.left)+countLeaves(root.right);}staticvoidMain(string[]args){// Representation of input binary tree// 1// / \// 2 3// / \// 4 5Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);Console.WriteLine(countLeaves(root));}}
JavaScript
classNode{constructor(data){this.data=data;this.left=null;this.right=null;}}functioncountLeaves(root){// If the root is null, return 0if(root===null){return0;}// If the node has no left or right child,// it is a leafif(root.left===null&&root.right===null){return1;}// Recursively count the leaves in the left // and right subtreesreturncountLeaves(root.left)+countLeaves(root.right);}// Representation of input binary tree// 1// / \// 2 3// / \// 4 5letroot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);console.log(countLeaves(root));
Output
3
Iterative Approach - O(n) Time and O(n) Space
The idea is to usethequeue basedlevel 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.
C++
#include<iostream>usingnamespacestd;structNode{intdata;Node*left,*right;Node(intval){data=val;left=right=nullptr;}};// Function to count the leaf nodes in a binary treeintcountLeaves(Node*root){// If the root is null, return 0if(root==nullptr){return0;}// Initialize a queue for level order traversalqueue<Node*>q;q.push(root);intcount=0;// Traverse the tree using level order traversalwhile(!q.empty()){Node*curr=q.front();q.pop();// Check if the current node is a leaf nodeif(curr->left==nullptr&&curr->right==nullptr){count++;}// Enqueue left and right children if they existif(curr->left!=nullptr){q.push(curr->left);}if(curr->right!=nullptr){q.push(curr->right);}}returncount;}intmain(){// Representation of input binary tree// 1// / \ // 2 3// / \ // 4 5Node*root=newNode(1);root->left=newNode(2);root->right=newNode(3);root->left->left=newNode(4);root->left->right=newNode(5);cout<<countLeaves(root)<<"\n";return0;}
Java
importjava.util.LinkedList;importjava.util.Queue;classNode{intdata;Nodeleft,right;Node(intval){data=val;left=right=null;}}classGfG{// Function to count the leaf nodes in a binary treestaticintcountLeaves(Noderoot){// If root is NULL, return 0if(root==null){return0;}// Initialize a queue for level order traversalQueue<Node>queue=newLinkedList<>();queue.add(root);intcount=0;// Traverse the tree using level order traversalwhile(!queue.isEmpty()){Nodecurr=queue.poll();// Check if the current node is a leaf nodeif(curr.left==null&&curr.right==null){count++;}// Enqueue left and right children if they existif(curr.left!=null){queue.add(curr.left);}if(curr.right!=null){queue.add(curr.right);}}returncount;}publicstaticvoidmain(String[]args){// Representation of input binary tree// 1// / \// 2 3// / \// 4 5Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);System.out.println(countLeaves(root));}}
Python
fromcollectionsimportdequeclassNode:def__init__(self,data):self.data=dataself.left=Noneself.right=NonedefcountLeaves(root):# If root is None, return 0ifrootisNone:return0# Initialize a queue for level order traversalqueue=deque([root])count=0# Traverse the tree using level order traversalwhilequeue:curr=queue.popleft()# Check if the current node is a leaf nodeifcurr.leftisNoneandcurr.rightisNone:count+=1# Enqueue left and right children if they existifcurr.leftisnotNone:queue.append(curr.left)ifcurr.rightisnotNone:queue.append(curr.right)returncountif__name__=="__main__":# Representation of input binary tree# 1# / \# 2 3# / \# 4 5root=Node(1)root.left=Node(2)root.right=Node(3)root.left.left=Node(4)root.left.right=Node(5)print(countLeaves(root))
C#
usingSystem;usingSystem.Collections.Generic;classNode{publicintdata;publicNodeleft,right;publicNode(intval){data=val;left=right=null;}}classGfG{staticintCountLeaves(Noderoot){// If the root is null, return 0if(root==null){return0;}// Initialize a queue for level order traversalQueue<Node>queue=newQueue<Node>();queue.Enqueue(root);// Variable to count leaf nodesintcount=0;// Traverse the tree using level order traversalwhile(queue.Count>0){Nodecurr=queue.Dequeue();// Check if the current node is a leaf nodeif(curr.left==null&&curr.right==null){count++;}// Enqueue left and right children if they existif(curr.left!=null){queue.Enqueue(curr.left);}if(curr.right!=null){queue.Enqueue(curr.right);}}returncount;}staticvoidMain(string[]args){// Representation of input binary tree// 1// / \// 2 3// / \// 4 5Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);Console.WriteLine(CountLeaves(root));}}
JavaScript
classNode{constructor(data){this.data=data;this.left=null;this.right=null;}}functioncountLeaves(root){// If the root is null, return 0if(root===null){return0;}// Initialize a queue for level order traversalconstqueue=[];queue.push(root);letcount=0;// Traverse the tree using level order traversalwhile(queue.length>0){constcurr=queue.shift();// Check if the current node is a leaf nodeif(curr.left===null&&curr.right===null){count++;}// Enqueue left and right children if they existif(curr.left!==null){queue.push(curr.left);}if(curr.right!==null){queue.push(curr.right);}}returncount;}// Representation of input binary tree// 1// / \// 2 3// / \// 4 5letroot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);console.log(countLeaves(root));