Code Logo

Tree Count Nodes at Level

Published at25 Jul 2026
Binary Tree Easy 1 views
Like0

Given an array representing a complete binary tree in level-order and a level number k (0-indexed), count how many nodes exist at that level. The root is at level 0, its children at level 1, and so on.

For example, in the tree [1, 2, 3, 4, 5, 6, 7], level 0 has 1 node (root), level 1 has 2 nodes (2, 3), level 2 has 4 nodes (4, 5, 6, 7). Level 3 has 0 nodes. An empty tree has 0 nodes at any level.

In a complete binary tree stored as an array, nodes at level k range from index 2^k - 1 to 2^(k+1) - 2. The number of nodes at that level is the count of valid indices within that range that exist in the array.

The solution calculates the start and end indices for the given level using the formula. It then counts how many of those indices are within the array bounds. The maximum possible nodes at level k is 2^k.

Edge cases include an empty tree (return 0), asking for a level deeper than the tree height (return 0), and level 0 (always 1 if the tree is non-empty).

Example Input & Output

Example 1
Input
[1,2,3,4,5,6,7],0
Output
1
Explanation

Root level has 1 node

Example 2
Input
[1,2,3,4,5,6,7],2
Output
4
Explanation

Level 2 has 4 nodes (indices 3-6)

Example 3
Input
[1,2,3,4,5,6,7],1
Output
2
Explanation

Level 1 has 2 nodes (indices 1,2)

Example 4
Input
[],0
Output
0
Explanation

Empty

Example 5
Input
[1,2,3,4,5],2
Output
2
Explanation

Level 2 has 2 nodes (indices 3,4)

Algorithm Flow

Recommendation Algorithm Flow for Tree Count Nodes at Level

Solution Approach

Calculate the index range for the given level and count valid entries within the array bounds.

function countAtLevel(arr, k)
  start = pow(2, k) - 1
  end = min(pow(2, k + 1) - 1, length(arr))
  count = 0
  for i = start to end - 1
    if i < length(arr) then count = count + 1
  return count

Compute start index as 2^k - 1 and end index as min(2^(k+1) - 1, array length). Iterate from start to end-1, counting indices that are within the array. This counts only existing nodes at the requested level.

Time complexity is O(2^k), space complexity is O(1).

Best Answers

java
class Solution {
    public int solution(int[] nums, int l) {
        if(nums.length==0)return 0;int s=(1<<l)-1,e=(1<<(l+1))-2;
        if(s>=nums.length)return 0;
        return Math.min(e,nums.length-1)-s+1;
    }
}