AlgoFrames

Range sum of a BST

Warm-up · Write code · about 10 min

Given the root of a binary search tree and two integers lo and hi, return the sum of all keys k with lo ≤ k ≤ hi.

Example 1

Input:

[[10,5,15,3,7,null,18],7,15]

Output:

32

The keys 7, 10 and 15 add up to 32.

Example 2

Input:

[[10,5,15,3,7,null,18],6,10]

Output:

17

The keys 7 and 10 add up to 17.

Constraints

  • 1 ≤ number of nodes ≤ 50
  • Keys are distinct integers with 0 ≤ key ≤ 100
  • 0 ≤ lo ≤ hi ≤ 100

Learn the idea first: Ordered sets and maps: floor, ceiling, range queries, a visual lesson.

More Ordered sets and maps: floor, ceiling, range queries problems