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.
Input: ([], 1, 10)
Expected Output: 0
Explanation: Empty tree: there are no nodes, so the range sum is 0.
Input: ([5], 5, 5)
Expected Output: 5
Explanation: Single node 5 with low = high = 5; 5 is in range, so the sum is 5.
Input: ([5], 6, 10)
Expected Output: 0
Explanation: Single node 5 is below the range [6,10], so nothing is summed -> 0.
Input: ([8, 3, 10, 1, 6, None, 14], 100, 200)
Expected Output: 0
Explanation: Every node value (1,3,6,8,10,14) is far below [100,200]; all right descents would still fall short, so the sum is 0.
Input: ([8, 3, 10, 1, 6, None, 14], -5, 50)
Expected Output: 42
Explanation: All six nodes (1+3+6+8+10+14) lie inside [-5,50], so the sum is 42.
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.