Find Range Sum Queries in a BST

viaGlassdoor

Problem: Given the root of a Binary Search Tree and a range [low, high], return the sum of values of all nodes with a value in the inclusive range.

Constraints: The tree can have up to 10^4 nodes; node values are unique integers.

Example: Input: root = [10,5,15,3,7,null,18], low=7, high=15 Output: 32 (7+10+15)

Approach: Exploit the BST property: perform a DFS/BFS, but prune branches outside the range - if node.val < low, only recurse right; if node.val > high, only recurse left; otherwise add node.val to the sum and recurse both sides. This avoids visiting the entire tree, giving better than O(n) performance for skewed ranges while remaining O(n) worst case.

Add a follow-up question they asked
No follow-ups yet. Be the first to add one.
asked …
LeaderboardSalary
Language
Account