Skip to content
Bill Liao
Go back

Range Sum of BST

Edit page

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].

Example 1:

Input: root = [10,5,15,3,7,null,18], low = 7, high = 15 Output: 32 Explanation: Nodes 7, 10, and 15 are in the range [7, 15]. 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: Nodes 6, 7, and 10 are in the range [6, 10]. 6 + 7 + 10 = 23.

Constraints:

Approach: DFS with BST Pruning (Optimal Solution)

Algorithm

  1. Recursively traverse the tree with a dfs(root) function
  2. If root is null, return 0
  3. Add root.val to the sum only if it lies within [low, high]
  4. Prune: if root.val > low, the left subtree may contain in-range values, so recurse left
  5. Prune: if root.val < high, the right subtree may contain in-range values, so recurse right
  6. Return the accumulated sum

Key Insight

In a BST, all nodes in the left subtree are smaller than root.val and all nodes in the right subtree are larger. This lets us prune whole subtrees: if the current node is already at or below low, the entire left subtree is out of range; if it is at or above high, the entire right subtree is out of range. Only branches that could contain in-range values are explored.

Time & Space Complexity

Java Implementation

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
public class RangeSumOfBst {

    public int rangeSumBST(TreeNode root, int low, int high) {
        return dfs(root, low, high);
    }

    private int dfs(TreeNode root, int low, int high) {
        if (root == null) {
            return 0;
        }
        int x = root.val;
        int ans = (low <= x && x <= high) ? x : 0;
        // Left subtree could contain in-range values
        if (x > low) {
            ans += dfs(root.left, low, high);
        }
        // Right subtree could contain in-range values
        if (x < high) {
            ans += dfs(root.right, low, high);
        }
        return ans;
    }
}

Example Walkthrough

For root = [10,5,15,3,7,null,18], low = 7, high = 15:

  1. Node 10 is in range → ans = 10. Since 10 > 7, recurse left; since 10 < 15, recurse right
  2. Node 5 < 7 → not added. 5 > 7 is false, so skip left; 5 < 15, recurse right → node 7
  3. Node 7 in range → ans += 7. 7 > 7 false (skip left); 7 < 15 true, recurse right (null) → 0
  4. Node 15 in range → ans += 15. 15 > 7, recurse left (null); 15 < 15 false (skip right)
  5. Total: 10 + 7 + 15 = 32

Alternative Approach: Iterative In-order Traversal

import java.util.ArrayDeque;
import java.util.Deque;

public class RangeSumBstIterative {

    public int rangeSumBST(TreeNode root, int low, int high) {
        int sum = 0;
        Deque<TreeNode> stack = new ArrayDeque<>();
        TreeNode cur = root;
        while (cur != null || !stack.isEmpty()) {
            while (cur != null) {
                stack.push(cur);
                cur = cur.left;
            }
            cur = stack.pop();
            if (cur.val >= low && cur.val <= high) {
                sum += cur.val;
            }
            if (cur.val > high) {
                break; // everything after is even larger
            }
            cur = cur.right;
        }
        return sum;
    }
}

The iterative in-order traversal accumulates values in ascending order and stops early once the current node exceeds high.

Key Insights

  1. Pruning Power: x > low and x < high conditions skip entire subtrees that cannot contain in-range values
  2. Inclusive Range: Both boundaries are included in the sum
  3. BST Property Utilization: Comparisons against low/high rely on the guaranteed ordering of left/right subtrees
  4. Early Stop: The in-order variant stops as soon as a node exceeds high

The DFS with pruning is the optimal solution, providing O(n) time and O(n) space in the worst case.


Edit page
Share this post:

Previous Post
Kth Smallest Element in a BST
Next Post
Binary Tree Level Order Traversal