AlgoInsight

DSA problem

Range Sum of BST

EasyBST / Ordered SetPattern: BST / Ordered Settop600FacebookAmazonGoogleMicrosoftApple

Given the root of a binary search tree and two integers low and high, return the sum of the values of all nodes whose values lie in the inclusive range [low, high].

The naive approach traverses the entire tree and adds up every node whose value is in range. That is correct and easy to write, but it ignores the BST ordering invariant and always touches all n nodes — wasteful when the range covers only a small slice of the tree.

The BST property lets us prune entire subtrees during the traversal. If the current node's value is strictly less than low, every value in its left subtree is even smaller, so we can skip the left subtree completely and only recurse right. Symmetrically, if the value is strictly greater than high, we skip the right subtree and only recurse left.

The optimal solution combines a DFS walk with this pruning. At each node: if node.val < low, recurse only on the right child; if node.val > high, recurse only on the left child; otherwise add node.val to the sum and recurse on both children. This visits the minimum set of nodes that could possibly contribute, running in O(n) time in the worst case but typically much faster, with O(h) recursion stack.

Examples

Example 1
Input: root = [10,5,15,3,7,null,18], low = 7, high = 15
Output: 32
Explanation: The nodes with values in [7, 15] are 7, 10, and 15. Their sum is 7 + 10 + 15 = 32.
Example 2
Input: root = [10,5,15,3,7,13,18,1,null,6], low = 6, high = 10
Output: 23
Explanation: In-range values are 6, 7, and 10, summing to 23.
Example 3
Input: root = [1], low = 1, high = 1
Output: 1
Explanation: The single node has value 1, which lies in the range, so the answer is 1.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

bsttreedfsrecursionpruning

Browse all DSA problems