Range Sum of BST

You're given the root node of a Binary Search Tree (BST) and two integers low and high. Your task is to find the sum of all node values that fall within the inclusive range [low, high].

A Binary Search Tree has a special property: for any node, all values in the left subtree are smaller, and all values in the right subtree are larger. This property allows us to optimize our search and skip entire branches that are guaranteed to be outside our target range.

Goal: Calculate the sum of all nodes with values between low and high (inclusive).

Example: If we have a BST with nodes [10, 5, 15, 3, 7, null, 18] and range [7, 15], we should sum up nodes with values 7, 10, and 15, giving us 32.

Input & Output

example_1.py โ€” Basic BST Range Sum
$ Input: root = [10,5,15,3,7,null,18], low = 7, high = 15
โ€บ Output: 32
๐Ÿ’ก Note: Nodes 7, 10, and 15 are in the range [7, 15]. Sum = 7 + 10 + 15 = 32
example_2.py โ€” Larger Range
$ Input: root = [10,5,15,3,7,13,18,1,null,6], low = 6, high = 10
โ€บ Output: 23
๐Ÿ’ก Note: Nodes 6, 7, and 10 are in the range [6, 10]. Sum = 6 + 7 + 10 = 23
example_3.py โ€” Single Node
$ Input: root = [5], low = 3, high = 7
โ€บ Output: 5
๐Ÿ’ก Note: Only one node with value 5, which is in range [3, 7], so sum = 5

Visualization

Tap to expand
$10$5$15$3$7$18Target Range: $7 - $15Found: $7 + $10 + $15 = $32Skipped expensive section (dashed line)
Understanding the Visualization
1
Start at Root
Begin at the root section and check if current shelf's book price is in our target range
2
Make Smart Decisions
If current book is too expensive, ignore all shelves to the right (they'll be even more expensive)
3
Prune Branches
If current book is too cheap, ignore all shelves to the left (they'll be even cheaper)
4
Sum Valid Books
Only visit and sum books that could potentially be in our price range
Key Takeaway
๐ŸŽฏ Key Insight: BST property allows us to eliminate entire subtrees, making the search much more efficient than checking every single node!

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(n)

We visit every node in the tree exactly once, where n is the total number of nodes

n
2n
โœ“ Linear Growth
Space Complexity
O(h)

Recursion stack space, where h is the height of the tree (O(log n) for balanced BST, O(n) for skewed tree)

n
2n
โœ“ Linear Space

Constraints

  • The number of nodes in the tree is in the range [1, 2 ร— 104]
  • 1 โ‰ค Node.val โ‰ค 105
  • 1 โ‰ค low โ‰ค high โ‰ค 105
  • All Node.val are unique (guaranteed BST property)
Asked in
Amazon 45 Google 38 Microsoft 32 Meta 28
95.0K Views
Medium Frequency
~15 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen