Code Logo

Tree Count Leaves

Published at25 Jul 2026
Tree Traversal Easy 0 views
Like0

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
Recommendation Algorithm Flow for Tree Count Leaves

Solution Approach

function solution(arr) {
  if (arr.length === 0) return 0;
  var count = 0, n = arr.length;
  for (var i = 0; i < n; i++) {
    if (2 * i + 1 >= n) count++;
  }
  return count;
}

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;
    }
}