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.
getLeafCount(node) 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
Leaf count for the above tree is 3.
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.
- Iterative program to count leaf nodes in a Binary Tree
- Print the longest leaf to leaf path in a Binary tree
- Construct XOR tree by Given leaf nodes of Perfect Binary Tree
- Count Non-Leaf nodes in a Binary Tree
- Count pairs of leaf nodes in a Binary Tree which are at most K distance apart
- Count root to leaf paths having exactly K distinct nodes in a Binary Tree
- Remove all leaf nodes from a Generic Tree or N-ary Tree
- Sum of all leaf nodes of binary tree
- Pairwise Swap leaf nodes in a binary tree
- Leaf nodes from Preorder of a Binary Search Tree (Using Recursion)
- Product of all leaf nodes of binary tree
- Print Sum and Product of all Non-Leaf nodes in Binary Tree
- Print the nodes of binary tree as they become the leaf node
- Print All Leaf Nodes of a Binary Tree from left to right | Set-2 ( Iterative Approach )
- Print leaf nodes in binary tree from left to right using one stack
- Print all leaf nodes of a binary tree from right to left
- Maximum sum of leaf nodes among all levels of the given binary tree
- Print left and right leaf nodes separately in Binary Tree
- Generate Complete Binary Tree in such a way that sum of non-leaf nodes is minimum
- Check if a Binary Tree consists of a pair of leaf nodes with sum K