GeeksforGeeks Easy

Floor in BST

Largest BST value ≤ x (the floor), or −1 if none.

bstbinary-search
Open on GeeksforGeeks ↗
02

Intuition

Walk the search path for x. Every node ≤ x is a floor candidate — remember the best and go right hoping for closer; every node > x is too big — go left. The walk ends with the tightest candidate.

How to spot this pattern

The mirror of ceil: the largest value not exceeding x. Same record-then-narrow skeleton, with both comparisons flipped. Recognising that these two problems are one problem with a sign change is worth more than memorising either — the same idea gives you inorder-successor and predecessor for free.

03

Approach

1

Candidates only from ≤

node.val == x → exact floor, stop. node.val < x → candidate; a better one may lurk right.

2

Too big → left

node.val > x contributes nothing; the floor must be in the left subtree.

3

One descent

No backtracking — the last recorded candidate is the answer.

04

Solution & live demo

1def floor_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 closer on the right
7 root = root.right
8 else:
9 root = root.left
10 return ans
05

Common pitfalls

Copying the ceil solution without flipping both halves

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

Two things flip between floor and ceil — which comparison stores a candidate, and which direction tightens it. Flipping only the comparison and keeping ceil's direction walks away from every better answer, so you return the first value below x rather than the largest.

Seeding the answer with a real value

✗ Wrong
ans = root.val
✓ Right
ans = -1

When every node exceeds x there is no floor, and the problem expects -1. Seeding from the root reports a value that is larger than x, which is not a floor at all.

06

Edge cases

x smaller than the minimum

No node qualifies; return −1 (or None).

x present exactly

Early exit with x itself.

07

Complexity

Time
O(h)
Space
O(1)
Single search-path walk.