#938

Range Sum of BST

Easy Pruned DFS

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Return the sum of all node values in a BST that lie in the range [low, high].

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: sum the values between low and high.

Why this works: skip whole subtrees that are out of range: below low → ignore the left side; above high → ignore the right side.

Example: 10 (5 (3, 7), 15 (-, 18)), range [7, 15]

7 + 10 + 15 = 32

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Visiting every node — correct, but it ignores the BST property.

Solve on LeetCode ↗
Complexity
  • Time: O(n) worst case, much less when the range is narrow.
  • Space: O(h).
Topic: Binary Search Trees
🎬 Episodes 61–63: video coming soon