Floor and ceiling
Standard · Write code · about 12 min
Given the root of a binary search tree and an integer target, return [floor, ceiling].
The floor is the largest key that is at most target. The ceiling is the smallest key that is at least target. Use -1 when there is no such key.
Example 1
Input:
[[40,20,60,10,30,50,70],45]
Output:
[40,50]
40 is the largest key at most 45. 50 is the smallest at least 45.
Example 2
Input:
[[40,20,60,10,30,50,70],30]
Output:
[30,30]
30 is stored, so it is both.
Constraints
- 1 ≤ number of nodes ≤ 50
- Keys are distinct integers with 0 ≤ key ≤ 100
- 0 ≤ target ≤ 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
- Range sum of a BST Warm-up
- Count in range Standard