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.

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

python
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

Edge cases

x smaller than the minimum

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

x present exactly

Early exit with x itself.

06

Complexity

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