
Problem
Solution
Submissions
Leaf Nodes in Binary Tree
Certification: Basic Level
Accuracy: 100%
Submissions: 1
Points: 8
Write a Java program to count the number of leaf nodes in a binary tree. A leaf node is a node that has no children (both left and right child pointers are null).
Example 1
- Input: Binary tree [1,2,3,4,5]
- Output: 3
- Explanation: Nodes 4, 5, and 3 are leaf nodes because they have no children.
Example 2
- Input: Binary tree [1,null,2,3]
- Output: 1
- Explanation: Only node 3 is a leaf node.
Constraints
- 0 ≤ Number of nodes ≤ 1000
- -1000 ≤ Node.val ≤ 1000
- Time Complexity: O(n) where n is the number of nodes
- Space Complexity: O(h) where h is the height of the tree
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Use a recursive approach to traverse the tree
- Check if a node is a leaf node (both left and right children are null)
- Increment the count whenever a leaf node is encountered
- Use pre-order, in-order, or post-order traversal to visit all nodes
- Alternatively, you can use iterative traversal with a stack or queue