Tree Count Nodes at Level
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
Root level has 1 node
Level 2 has 4 nodes (indices 3-6)
Level 1 has 2 nodes (indices 1,2)
Empty
Level 2 has 2 nodes (indices 3,4)
Algorithm Flow
Solution Approach
Calculate the index range for the given level and count valid entries within the array bounds.
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
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.
