Floor in BST
Floor in BST is a easy trees & bst problem solved with the miscellaneous bst questions pattern.
The best approach, optimal (walk down the bst), runs in O(h) time and O(1) space.
Below are 2 approaches in Java, from traverse everything up.
Problem
Given a BST and a value x, return the floor of x in the tree: the largest value that is less than or equal to x, or -1 if there is none.
Examples
Example 1
- Input
root = [10, 5, 15, 2, 6], x = 7- Output
6
Example 2
- Input
root = [10, 5, 15, 2, 6], x = 1- Output
-1
Constraints
- The tree has
1to10^5nodes. - Return -1 if no value is <= x.
Animated walkthrough
A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
Solutions
Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the Java code.
| Approach | Time | Space |
|---|---|---|
| Traverse everything | O(n) | O(h) |
| Optimal (walk down the BST) | O(h) | O(1) |
1Traverse everything
O(n)O(h)Visit every node and keep the largest value that is still <= x.
- DFS all nodes; track the best value <= x.
class Solution {
public static int floor(TreeNode root, int x) {
if (root == null) return -1;
int best = root.val <= x ? root.val : -1;
return Math.max(best, Math.max(floor(root.left, x), floor(root.right, x)));
}
}2Optimal (walk down the BST)
O(h)O(1)At each node: equal returns it; greater than x means the floor is to the left; smaller means it is a candidate, and a better one may be to the right.
- ans = -1.
- val == x → return x. val > x → go left. Else ans = val, go right.
class Solution {
public static int floor(TreeNode root, int x) {
int ans = -1;
while (root != null) {
if (root.val == x) return x;
if (root.val > x) root = root.left;
else { ans = root.val; root = root.right; }
}
return ans;
}
}Edge cases to test
- x equals a node (the answer is that node)
- x below the minimum
Hints
Hint 1
Like predecessor, but equal counts: a node <= x is a candidate, so go right to look for a bigger one.
FAQ
What is the best time complexity for Floor in BST?
Optimal (walk down the BST) runs in O(h) time and O(1) extra space.
Which pattern does Floor in BST use?
It is a trees & bst problem that uses the miscellaneous bst questions pattern. Other problems with the same pattern: Inorder Successor in BST, Inorder predecessor, Ceil in BST.
Is there a brute force solution for Floor in BST?
Yes. Traverse everything takes O(n) time and O(h) space. Visit every node and keep the largest value that is still <= x.
Which edge cases should I test for Floor in BST?
x equals a node (the answer is that node); x below the minimum.