GeeksforGeeks Easy

Ceil in BST

Smallest BST value ≥ x (the ceiling), or −1 if none.

bstbinary-search
Open on GeeksforGeeks ↗
02

Intuition

Exact mirror of floor: nodes ≥ x are candidates (then look left for tighter); nodes < x force a right turn.

How to spot this pattern

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.

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

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

Common pitfalls

Returning as soon as a valid candidate is found

✗ Wrong
if root.val > x:
    return root.val
✓ Right
if root.val > x:
    ans = root.val
    root = root.left

The 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

✗ Wrong
if root.val > x:
    ans = root.val
    root = root.right
✓ Right
if root.val > x:
    ans = root.val
    root = root.left

Everything 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.)

06

Edge cases

x larger than the maximum

No candidate ever recorded → −1.

x exactly present

Immediate return of x.

07

Complexity

Time
O(h)
Space
O(1)
Mirror of floor.