02
Intuition
Exact mirror of floor: nodes ≥ x are candidates (then look left for tighter); nodes < x force a right turn.
03
Approach
1
≥ is a candidate
Record and go left — maybe something smaller still clears x.
2
< goes right
Everything in the left subtree is even smaller; the ceiling lives right.
3
Symmetry with floor
Swap the comparison and the recorded side — worth writing both once to internalize.
04
Solution & live demo
python
▶1def ceil_bst(root, x):
▶2 ans = -1
▶3 while root:
▶4 if root.val == x: return x
▶5 if root.val > x:
▶6 ans = root.val # candidate; try tighter on the left
▶7 root = root.left
▶8 else:
▶9 root = root.right
▶10 return ans
05
Edge cases
x larger than the maximum
No candidate ever recorded → −1.
x exactly present
Immediate return of x.
06
Complexity
Time
O(h)
Space
O(1)
Mirror of floor.