Floor in BST
Iterative candidate tracking down one root-to-leaf path
At any node, one comparison against x settles two things at once. If the node's value is <= x, it is a legal candidate for the floor and the pointer moves right chasing a tighter one; if it exceeds x, it and its whole right subtree are disqualified and the pointer moves left. Tracking the best candidate seen so far turns this into a single root-to-leaf walk instead of a full traversal.
Details
Animated on: Given a BST and an integer x, find the floor of x: the largest value in the tree that is <= x, or -1 if none exists. root=[6,2,8,0,4,7,9,null,null,3,5], x=10 -> 9.
Problem:Floor in BSTEasy
Iterative candidate tracking down one root-to-leaf path
step 1 / 12
Call stack
Floor of 10. Initialize floor = -1 (no candidate found yet) and point node at the root, 6.
1FUNCTION floorBST(root, x):2 floor <- -13 node <- root4 WHILE node != null:5 IF node.val = x:6 RETURN node.val7 ELSE IF node.val < x:8 floor <- node.val9 node <- node.right10 ELSE:11 node <- node.left12 RETURN floor
← / → step · space play · Home restart
Every step in words
Show all 12 steps
- Floor of 10. Initialize floor = -1 (no candidate found yet) and point node at the root, 6.
- node holds 6, which is non-null, so we enter the loop and inspect this node.
- Is 6 < 10? Yes — 6 is a valid candidate (everything larger might still fit), so record floor = 6. A tighter candidate can only live to the right.
- node <- node.right. The pointer moves to 8, looking for a candidate closer to 10 than 6.
- node holds 8, which is non-null, so we enter the loop and inspect this node.
- Is 8 < 10? Yes — 8 is a valid candidate (everything larger might still fit), so record floor = 8. A tighter candidate can only live to the right.
- node <- node.right. The pointer moves to 9, looking for a candidate closer to 10 than 8.
- node holds 9, which is non-null, so we enter the loop and inspect this node.
- Is 9 < 10? Yes — 9 is a valid candidate (everything larger might still fit), so record floor = 9. A tighter candidate can only live to the right.
- node <- node.right, but 9 has no right child — node becomes null, so the walk ends with floor = 9.
- node is null — the walk is over. The loop exits with the best candidate recorded so far.
- Return floor = 9. Three comparisons (6 → 8 → 9) walked straight down the right spine, updating the candidate each time a node stayed under 10, and the left subtree (2, 0, 4, 3, 5) was never even visited.
Now solve it yourself
Watching is the first half. The second is writing it without the animation.