Given the root of a binary search tree and an integer key, return the ceil of key — the smallest value in the BST that is greater than or equal to key. If no such value exists, return -1.
The tree is given in level-order (breadth-first), using null for missing children.
<= key: record when the node is <= key and go right instead.<= key, then go right to find a larger valid value.Input: root = [8, 4, 12, 2, 6, 10, 14], key = 5 Output: 6 The smallest value >= 5 in the tree is 6.
Input: root = [8, 4, 12, 2, 6, 10, 14], key = 15 Output: -1 No value is >= 15.
- The number of nodes is in the range [1, 10^5] - 1 <= Node.val <= 10^5 - root is a valid BST - 0 <= key <= 10^5
Ceil is a guided descent. At each node: if it equals the key, that's the ceil. If it's smaller than the key, it can't be the ceil, and only the right subtree holds larger values — go right. If it's greater than or equal, it's a valid candidate, so remember it and go left to look for an even smaller valid value. One walk down — O(height).
“What is the ceil?”
The smallest value that is >= key.
“What if key is larger than everything?”
Return -1 — no value qualifies.
Ceil is the smallest value at least key, so I descend, and whenever a node is >= key I record it as a candidate and go left to try to beat it.
When a node is smaller than key, only its right subtree can help, so I go right.
Worked example — BST [8, 4, 12, 2, 6, 10, 14], key = 5
8 >= 5 -> candidate 8, go left 4 < 5 -> go right 6 >= 5 -> candidate 6, go left (null) -> ceil = 6
A node smaller than the key can never be the ceil; its right subtree might hold one.
A recorded candidate might be beaten by a smaller valid value on its left.
It's one root-to-leaf descent — O(log n) balanced, O(n) worst case.
| Recursive descent | Iterative descent | |
|---|---|---|
| Idea | Recurse the correct side, track candidate | Loop, track candidate |
| Time | O(height) | O(height) |
| Space | O(height) | O(1) |
Both are the same O(height) walk. Full code is in the Approaches selector below.
Key takeaway
Descend the BST: v == key returns v; v < key go right; v >= key record v and go left. The last recorded value is the ceil (or -1). O(height), O(1) iterative.
while node:
if v == key: return v
if v < key: node = node.right
else: ans = v; node = node.left