← DiffPush

Ceil in a Binary Search Tree

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

The Next-Available Slot Finder

A clinic's booking system files slot durations in a sorted tree. A walk-in needs the earliest slot that fits their procedure — the smallest filed duration that is at least as long as the request. The scheduler descends the tree once: whenever the current slot is long enough it is remembered as a candidate and the search tries smaller ones on the left; otherwise it goes right. No candidate after the whole descent means no slot qualifies.

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

Output: Return the smallest tree value greater than or equal to x, or -1 if no such value exists.

Constraints

Examples

Example 1

Input: {"tree":[5,1,7,null,2,null,null,null,3],"x":3}
Output: 3
3 exists in the tree, so the ceil of 3 is 3 itself.

Example 2

Input: {"tree":[5,1,7,null,2,null,null,null,3],"x":4}
Output: 5
Values at least 4 are 5 and 7; the smallest qualifying one is 5.

Solve this in your browser →

Also on LeetCode ↗