Community Problem

Range Sum of BST

Difficulty: Easy

Sum every BST value within an inclusive range, pruning subtrees that fall outside.

Range Sum of BST

Sum every BST value within an inclusive range, pruning subtrees that fall outside.

EASY
Free
trees
bst
dfs
recursion
ninarossi

By @ninarossi

February 16, 2026

·

Updated May 18, 2026

506 views

16

Rate

I see this one trip up engineers who treat the BST like a generic binary tree. The naive recursion that visits every node is correct, but it throws away the entire reason BSTs exist (ordered traversal). The interview signal here is whether you can spot the pruning opportunity: when the current node's value is below low, the entire LEFT subtree is guaranteed to also be below low, and you skip it.

Range Sum of BST

Given the root 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].

Examples

Example 1:

  • Input: root = [10, 5, 15, 3, 7, null, 18], low = 7, high = 15
  • Output: 32
  • Explanation: Nodes in [7, 15] are 7, 10, 15, summing to 32.

Example 2:

  • Input: root = [10, 5, 15, 3, 7, 13, 18, 1, null, 6], low = 6, high = 10
  • Output: 23
  • Explanation: Nodes in [6, 10] are 6, 7, 10, summing to 23.

Example 3:

  • Input: root = [4, 2, 6, 1, 3, 5, 7], low = 4, high = 4
  • Output: 4
  • Explanation: Only the root falls in the singleton range.

Example 4:

  • Input: root = [4, 2, 6, 1, 3, 5, 7], low = 8, high = 10
  • Output: 0
  • Explanation: No node falls in the range.

Constraints

  • The number of nodes in the tree is in the range [1, 2 * 10^4].
  • 1 <= Node.val <= 10^5.
  • 1 <= low <= high <= 10^5.
  • All Node.val are unique.

Follow-up

What is the worst-case complexity of the pruned solution on a perfectly balanced BST whose range covers all values? On a degenerate (linked-list-shaped) BST?

Solution

Hints

0/4
Hint 1
Hint 2
Hint 3
Hint 4
All Problems