Tree Count Nodes at Level
Published at25 Jul 2026
Created by M Ichsanul Fadhil
Given an array representing a binary tree and a level number, count how many nodes exist at that level. Level 0 is the root. In array representation, level n has indices from 2^n-1 to min(2^(n+1)-2, len-1).
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
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;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
