Tree Count Leaves
Given an array representing a complete binary tree in level-order, collect all leaf node values and return them in order. Leaf nodes are nodes that have no children — in the array representation, a node at index i is a leaf if its left child index (2i+1) is beyond the array bounds.
For example, in the tree [1, 2, 3, 4, 5, 6, 7], the leaves are 4, 5, 6, 7 (all at the bottom level). In [1, 2, 3, 4], the leaves are 3 and 4 (2 has a child, but 3 and 4 do not). An empty tree returns an empty array.
Leaf node identification is a fundamental tree operation. Leaves are the terminal nodes of a tree — they have no children and represent the end of every root-to-leaf path. In BST problems, leaves often serve as base cases for recursive algorithms.
The solution iterates through the array and checks each node. If its left child index is out of bounds, it is a leaf. Collect all such nodes into a result array.
Edge cases include an empty tree (return []), a single-node tree (the root is also a leaf), and a full tree where all leaves are at the same depth.
Example Input & Output
Leaves at 3,4,5,6
Root is leaf
Leaves at 2,3,4
Leaves at 2,3
Empty
Algorithm Flow
Solution Approach
Iterate through the array and collect nodes whose children are beyond the array bounds.
Loop through each index. A node is a leaf if its left child index (2i+1) is beyond the array length. In a complete binary tree, if the left child is out of bounds, the right child (2i+2) will also be out of bounds.
Time complexity is O(n), space complexity is O(n) for the result.
Best Answers
class Solution {
public int solution(int[] nums) {
if(nums.length==0)return 0;int c=0,n=nums.length;
for(int i=0;i<n;i++){if(2*i+1>=n)c++;}
return c;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
