Intuition
Exact mirror of floor: nodes ≥ x are candidates (then look left for tighter); nodes < x force a right turn.
Ceil and floor share one shape: you're looking for the best value on one side of x, so you keep a candidate and keep trying to improve it. Whenever a search can't hit exactly and must settle for the nearest, the pattern is record-then-narrow — save the current node as a fallback, then walk toward a tighter one.
Approach
≥ is a candidate
Record and go left — maybe something smaller still clears x.
< goes right
Everything in the left subtree is even smaller; the ceiling lives right.
Symmetry with floor
Swap the comparison and the recorded side — worth writing both once to internalize.
Solution & live demo
Common pitfalls
Returning as soon as a valid candidate is found
if root.val > x:
return root.valif root.val > x:
ans = root.val
root = root.leftThe first value above x is a valid upper bound, not the smallest one. In a BST there may be a closer candidate further left, so you record this one and keep narrowing — only when you run out of tree is the saved candidate final.
Going the wrong way after saving the candidate
if root.val > x:
ans = root.val
root = root.rightif root.val > x:
ans = root.val
root = root.leftEverything to the right is even larger, so it can never beat the candidate you just stored. To tighten a ceiling you must look at smaller values — that's the left subtree. (Floor is the exact mirror.)
Edge cases
No candidate ever recorded → −1.
Immediate return of x.