Tree Count Leaves
Published at25 Jul 2026
Created by M Ichsanul Fadhil
Count the number of leaf nodes in a binary tree represented as an array (root at index 0, children at 2i+1 and 2i+2). A leaf node has no children — in array representation, index i is a leaf if 2i+1 is beyond the array length or both children are null.
For each node at index i, check if it has children. If not, it's a leaf.
Example Input & Output
Example 1
Input
[1,2,3,4,5,6,7]
Output
4
Explanation
Leaves at 3,4,5,6
Example 2
Input
[1]
Output
1
Explanation
Root is leaf
Example 3
Input
[1,2,3,4,5]
Output
3
Explanation
Leaves at 2,3,4
Example 4
Input
[1,2,3,4]
Output
2
Explanation
Leaves at 2,3
Example 5
Input
[]
Output
0
Explanation
Empty
Algorithm Flow

Recommendation Algorithm Flow for Tree Count Leaves
Solution Approach
Best Answers
java
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.
