Range Sum of BST - Problem
Given the root node of a binary search tree and two integers low and high, return the sum of values of all nodes with a value in the inclusive range [low, high].
A Binary Search Tree (BST) is a tree where for every node, all values in the left subtree are smaller than the node's value, and all values in the right subtree are greater than the node's value.
Input & Output
Example 1 — Basic BST
$
Input:
root = [10,5,15,3,7,null,18], low = 7, high = 15
›
Output:
32
💡 Note:
Nodes 7, 10, and 15 are in range [7,15]. Sum = 7 + 10 + 15 = 32
Example 2 — Smaller 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 range [6,10]. Sum = 6 + 7 + 10 = 23
Example 3 — Single Node
$
Input:
root = [5], low = 3, high = 8
›
Output:
5
💡 Note:
Only node 5 exists and it's in range [3,8]. Sum = 5
Constraints
- The number of nodes in the tree is in the range [1, 2 × 104]
- 1 ≤ Node.val ≤ 105
- 1 ≤ low ≤ high ≤ 105
Visualization
Tap to expand
Understanding the Visualization
1
Input BST
Binary Search Tree with range [7, 15]
2
Find Range
Identify nodes with values in [7, 15]
3
Sum Values
Add up all qualifying node values
Key Takeaway
🎯 Key Insight: Use BST property to prune subtrees that cannot contain values in the target range
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code