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.
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.
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.
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 email@example.com. 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.
- Print All Leaf Nodes of a Binary Tree from left to right | Set-2 ( Iterative Approach )
- Program to count leaf nodes in a binary tree
- Deepest right leaf node in a binary tree | Iterative approach
- Deepest left leaf node in a binary tree | iterative approach
- Print the longest leaf to leaf path in a Binary tree
- Construct XOR tree by Given leaf nodes of Perfect Binary Tree
- Count half nodes in a Binary tree (Iterative and Recursive)
- Count full nodes in a Binary tree (Iterative and Recursive)
- Count Non-Leaf nodes in a Binary Tree
- Count root to leaf paths having exactly K distinct nodes in a Binary Tree
- Count pairs of leaf nodes in a Binary Tree which are at most K distance apart
- Check if a binary tree is subtree of another binary tree using preorder traversal : Iterative
- Check whether a binary tree is a full binary tree or not | Iterative Approach
- Remove all leaf nodes from a Generic Tree or N-ary Tree
- Sum of nodes at maximum depth of a Binary Tree | Iterative Approach
- 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