Skip to problem
←

Count BST Nodes in a Range

Medium 0 attempts

You're given a binary search tree and two bounds l and h. Count how many of the tree's nodes have a value falling within [l, h], inclusive on both ends.

Function contract

Implement countInRange(root, l, h). The runner converts the level-order array into nodes with val, left, and right fields. The bounds l and h are inclusive.

Output: The number of nodes whose values are at least l and at most h.

Example 1

Input
root = [10,5,50,1,null,40,100]
l = 5
h = 45
Output
3

Explanation: The values 5, 10, and 40 lie in [5,45], so the count is 3.

Example 2

Input
root = [10]
l = 11
h = 20
Output
0
Constraints
  • 1 <= number of nodes <= 10^4
  • 1 <= l <= h <= 10^5
  • The input is a valid BST with integer node values.

Pruned Iterative DFS

Count nodes in the range and skip subtrees whose values cannot fall inside it.

javascript
function countInRange(root, l, h) {
  const stack = root ? [root] : [];
  let count = 0;
  while (stack.length) {
    const node = stack.pop();
    if (node.val >= l && node.val <= h) count++;
    if (node.left && node.val >= l) stack.push(node.left);
    if (node.right && node.val <= h) stack.push(node.right);
  }
  return count;
}

Time: O(n) in the worst case; pruning can skip irrelevant subtrees. Space: O(H) auxiliary stack space, where H is the tree height (not the upper range bound h).

Loading discussion…

Saved in this browser only. Private to you.

JavaScript