← DiffPush

Floor in a Binary Search Tree

Baseline Binary Search Trees · Practice Problems O(h) · O(1)

The Best-Fit Locker Lookup

A sports warehouse shelves gear by size in a sorted tree, and a customer asks for the largest stocked size that still fits their frame — nothing bigger than the measurement. One descent answers it: whenever the current shelf fits, it becomes the running best and the clerk probes for an even better fit on the right; an oversized shelf sends the search left. Running out of tree without any fit means nothing qualifies.

Input: A binary search tree as a level-order array (null marks a missing child) and an integer x — the measurement.

Output: Return the greatest tree value less than or equal to x, or -1 if every stocked value is bigger.

Constraints

Examples

Example 1

Input: {"tree":[10,5,15,2,7],"x":6}
Output: 5
Values at most 6 are 2 and 5 (7 overshoots), so the best fit is 5.

Example 2

Input: {"tree":[10,5,15,2,7],"x":13}
Output: 10
The largest value not exceeding 13 is 10.

Solve this in your browser →

Also on LeetCode ↗