Skip to problem
←

Range Sum of BST

Easy 0 attempts

Given a binary search tree root and two bounds low and high, return the sum of every node value in the inclusive interval [low, high].

Include both boundary values when present. The bounds need not occur in the tree. Sum qualifying nodes anywhere in the tree, not just along one path, and return 0 when none qualify. Leave the tree unchanged.

For root = [10, 5, 15, 3, 7, null, 18], low = 7, and high = 15, the qualifying values are 7, 10, and 15, giving 32.

Examples use level-order arrays with null for missing children. Your function receives nodes with val, left, and right properties.

Function contract

Implement rangeSumBST(root, low, high). Trees use level-order arrays with null for missing children. The editor passes nodes with val, left, and right properties; [] becomes null.

Output: Return the sum of all node values v satisfying low <= v <= high; return 0 if no node qualifies.

Example 1

Input
root = [10,5,15,3,7,null,18]
low = 7
high = 15
Output
32

Example 2

Input
root = [1]
low = 2
high = 3
Output
0
Constraints
  • 1 <= number of nodes <= 2 * 10^4
  • 1 <= Node.val <= 10^5
  • 1 <= low <= high <= 10^5
  • All node values are distinct, and the tree satisfies strict BST ordering.

Pruned Iterative DFS

Use an explicit stack to visit candidate nodes. Add a node's value when it lies between both bounds, inclusive.

If a node's value is no greater than low, its entire left subtree is strictly below the range and can be skipped. Similarly, when the node's value is at least high, its right subtree is strictly above the range. These pruning rules rely on distinct values and strict BST ordering.

The stack avoids recursive call-stack limits for long, one-sided trees. Reading child pointers without modifying them preserves the input.

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

Time: O(n) in the worst case, with out-of-range branches pruned | Space: O(h), where h is tree height.

Loading discussion…

Saved in this browser only. Private to you.

JavaScript