A node is a leaf node if both left and right child nodes of it are NULL. Here is an algorithm to get the leaf node count.
1) If node is NULL then return 0.
2) Else If left and right child nodes are NULL return 1.
3) Else recursively calculate leaf count of the tree using below formula.
Leaf count of a tree = Leaf count of left subtree +
Leaf count of right subtree
Console.WriteLine("The leaf count of binary tree is : "+ tree.LeafCount);
// This code is contributed by Shrikant13
/* A binary tree node has data,
pointer to left child and
a pointer to right child */
this.left = null;
this.right = null;
this.data = data;
/* Function to get the count
of leaf nodes in a binary tree*/
if(node == null)
if(node.left == null&& node.right == null)
/* Helper function that allocates a new node with the
given data and NULL left and right pointers. */
let Node = newnode(data);
/*create a tree*/
let 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*/
document.write("The leaf count of binary tree is : "+ getLeafCount(root));
// This code is contributed by mukesh07.
The leaf count of binary tree is : 3
Time & Space Complexities: Since this program is similar to traversal of tree, time and space complexities will be same as Tree traversal (Please see our Tree Traversal post for details)
Please write comments if you find any bug in the above programs/algorithms or other ways to solve the same problem.
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. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
In case you wish to attend live classes with industry experts, please refer DSA Live Classes