Range Sum of BST

Easy BSTTreeDFS

Problem

Given the root of a BST and integers low and high, return the sum of all node values in the inclusive range [low, high].

Example 1 Input: root = [10,5,15,3,7,null,18], low = 7, high = 15 Output: 32
Example 2 Input: root = [10,5,15,3,7,13,18,1,null,6], low = 6, high = 10 Output: 23

Constraints

Approach — Tree Traversal

This is a Tree Traversal problem. The idea: traverse the tree — DFS recursively, or BFS level by level — and combine the results from each subtree. Work through the reference code below line by line, then re-derive it yourself in the editor — that's how the pattern sticks.

Complexity: O(n) time.

Solution code

Python

class Solution:
    def rangeSumBST(self, root, low, high):
        if not root:
            return 0
        if root.val < low:
            return self.rangeSumBST(root.right, low, high)
        if root.val > high:
            return self.rangeSumBST(root.left, low, high)
        return root.val + self.rangeSumBST(root.left, low, high) + self.rangeSumBST(root.right, low, high)

Java

class Solution {
    public int rangeSumBST(TreeNode root, int low, int high) {
        if (root == null) return 0;
        if (root.val < low)  return rangeSumBST(root.right, low, high);
        if (root.val > high) return rangeSumBST(root.left,  low, high);
        return root.val + rangeSumBST(root.left, low, high) + rangeSumBST(root.right, low, high);
    }
}

Practice it

Reading a solution isn't the same as being able to write it under pressure. Open this problem in the in-browser editor, hide the solution, and solve it from scratch — your code runs against real test cases instantly.

Solve Range Sum of BST interactively → ← All solutions