Range Sum of BST (LeetCode 938): Solution and Explanation
You get the root of a binary search tree and two bounds, low and high. Add up the values of every node that falls inside the inclusive range [low, high] and return the total.
Intuition
Any traversal that visits every node and adds the values in range gives the right answer. That ignores the one fact the problem hands you: the tree is a binary search tree, so every value in a left subtree is smaller than its parent and every value in a right subtree is larger.
That ordering lets a single comparison rule out an entire subtree. If a node's value is at most low, everything on its left is smaller still, so none of it can be in range. If a node's value is at least high, everything on its right is larger, so that side is out too.
Picture the nodes laid out left to right in sorted order. The values in range form one contiguous band. The pruned walk only steps into subtrees that overlap that band, and cuts off the rest without looking at them.
Approach: Iterative DFS with BST pruning
- Set
total = 0and push the root onto a stack. - Pop a node. If
low <= node.val <= high, add its value tototal. - Push the left child only when
node.val > low, because only then can the left side hold values that are at leastlow. - Push the right child only when
node.val < high, because only then can the right side hold values that are at mosthigh. - When the stack is empty, return
total.
Step-by-step example
root = [10,5,15,3,7,null,18], low = 7, high = 15
- Push 10. Pop 10: it is in [7, 15], so total = 10. 10 > 7 and 10 < 15, so push both 5 and 15.
- Pop 15: in range, total = 25. 15 > 7 but there is no left child. 15 is not below 15, so the right child 18 is skipped without a visit.
- Pop 5: below 7, so it does not count. 5 <= 7 means its left child 3 is skipped. 5 < 15, so push its right child 7.
- Pop 7: in range, total = 32. It has no children.
- The stack is empty after visiting 4 of 6 nodes. Return 32.
Code: Python, Java, C++
1class Solution:
2 def rangeSumBST(self, root: Optional[TreeNode], low: int, high: int) -> int:
3 total = 0
4 stack = [root] if root else []
5 while stack:
6 node = stack.pop()
7 if low <= node.val <= high:
8 total += node.val
9 if node.left and node.val > low:
10 stack.append(node.left)
11 if node.right and node.val < high:
12 stack.append(node.right)
13 return total1class Solution {
2 public int rangeSumBST(TreeNode root, int low, int high) {
3 int total = 0;
4 Deque<TreeNode> stack = new ArrayDeque<>();
5 if (root != null) stack.push(root);
6 while (!stack.isEmpty()) {
7 TreeNode node = stack.pop();
8 if (low <= node.val && node.val <= high) {
9 total += node.val;
10 }
11 if (node.left != null && node.val > low) {
12 stack.push(node.left);
13 }
14 if (node.right != null && node.val < high) {
15 stack.push(node.right);
16 }
17 }
18 return total;
19 }
20}1class Solution {
2public:
3 int rangeSumBST(TreeNode* root, int low, int high) {
4 int total = 0;
5 stack<TreeNode*> st;
6 if (root) st.push(root);
7 while (!st.empty()) {
8 TreeNode* node = st.top();
9 st.pop();
10 if (low <= node->val && node->val <= high) {
11 total += node->val;
12 }
13 if (node->left && node->val > low) {
14 st.push(node->left);
15 }
16 if (node->right && node->val < high) {
17 st.push(node->right);
18 }
19 }
20 return total;
21 }
22};Time and space complexity
O(n)
In the worst case every node is in range and must be visited. When the range is narrow, the pruning skips whole subtrees, and on a balanced tree the work drops to about O(log n + k) where k is the number of values in range.
O(h)
The stack holds at most a path's worth of pending siblings, which is bounded by the tree height h. That is O(log n) for a balanced tree and O(n) for a skewed one.
Other approaches
Full traversal without pruning (time O(n), space O(h))
Visit every node with any traversal and add the values in range. It is correct and simple, but it never uses the BST property, so it always touches all n nodes.
Recursive pruned DFS (time O(n), space O(h))
The same pruning written recursively: if the node is below low, recurse right only; if above high, recurse left only; otherwise add the value and recurse both ways. It is shorter, but deep skewed trees use the call stack.
Inorder traversal with early stop (time O(n), space O(h))
An inorder walk produces values in sorted order, so you can start adding once values reach low and stop as soon as one passes high.
Common mistakes
- Pruning with strict comparisons on the wrong side. A node equal to
lowstill counts, but its left subtree does not, so the left check isnode.val > low, not>=. - Stopping at the first out-of-range node. A node below
lowcan still have in-range values in its right subtree, so you must keep exploring that side. - Forgetting that the bounds are inclusive and writing
low < node.val < highfor the add check. - Using recursion on a tree with 20,000 nodes in a straight line, which can exceed the default recursion limit in Python.
Frequently asked questions
Why can the left subtree be skipped when node.val <= low?
Every value in a node's left subtree is smaller than the node. If the node is already at or below low, those values are all below low, so none of them can be in range.
Does pruning change the worst-case complexity?
No. If every value lies in [low, high], every node must be added and visited, which is O(n). Pruning helps on narrow ranges, where it can skip most of the tree.
Would this work on a binary tree that is not a BST?
Only without the pruning. The skip rules depend on the ordering of a binary search tree; on a general tree you would have to visit every node.
Is the iterative or the recursive version better?
Both do the same work. The iterative version with an explicit stack avoids recursion depth limits on very deep trees, which matters for skewed inputs.