AlgoFrames

Count in range

Standard · Write code · about 12 min

Given the root of a binary search tree and two integers lo and hi, return how many keys k satisfy lo ≤ k ≤ hi.

Skip every subtree that cannot hold a key in the range.

Example 1

Input:

[[40,20,60,10,30,50,70],25,55]

Output:

3

The keys 30, 40 and 50 lie in the range.

Example 2

Input:

[[40,20,60,10,30,50,70],0,100]

Output:

7

Every key lies in the range.

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