Compute BST range sum
Company: Meta
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Onsite
Quick Answer: This question evaluates understanding of binary search tree properties, traversal techniques, and the ability to implement both recursive and iterative algorithms while reasoning about time and space complexity.
Constraints
- 0 <= number of nodes <= 2 * 10^4
- Each node value fits in a 32-bit signed integer
- All node values in the BST are distinct
- -10^9 <= low <= high <= 10^9
- The input array is a valid level-order encoding of a BST (None marks a missing child)
Examples
Input: ([10, 5, 15, 3, 7, None, 18], 7, 15)
Expected Output: 32
Explanation: Tree rooted at 10 with children 5 and 15; values in [7,15] are 7, 10, 15 -> 7+10+15 = 32.
Input: ([10, 5, 15, 3, 7, 13, 18, 1, None, 6], 6, 10)
Expected Output: 23
Explanation: Values in [6,10] are 6, 7, 10 -> 6+7+10 = 23. The subtrees rooted at 13/15/18 and at 3 (mostly) are pruned by BST bounds.
Hints
- Use the BST ordering to avoid visiting subtrees that cannot contain in-range values: at a node with value v, skip the left subtree when v <= low and skip the right subtree when v >= high.
- With the array encoding, the left child of index i is at 2*i+1 and the right child is at 2*i+2 — recurse on those indices instead of pointer children.
- Handle the empty tree (empty array or a None root) by returning 0 before any traversal.
- An iterative version can replace recursion with an explicit stack of indices, applying the same two pruning checks before pushing a child.