Trees & Ordered Maps Hard
BST Ceiling Lookup
Build a binary search tree by inserting keys in order, then trace the source's tail-recursive search for the smallest key at least the target.
Trace input
Bounded JSONEdit the lesson input, then build a deterministic source-linked trace.
Source scenarios
Complexity
BestO(1) search after construction when the root is an exact match
AverageO(h) search, where h is tree height
WorstO(n) search in a skewed tree; O(n²) insertion for sorted keys
SpaceO(n) tree plus O(h) Java recursion during tree construction and tail calls
Array state
Follow the active comparisons and writes.
Current operation
Trace stateReady to explore
Source behavior & common mistakes
Follow duplicate-left insertion, each tail call, and the currentBest candidate until an exact match or empty subtree returns the answer.
- An exact key returns immediately, even if a candidate was recorded earlier.
- When a key is above the target, the source keeps the smaller candidate and searches left.
- When a key is below the target, the source searches right without changing currentBest.
- BSTNode.add sends equal keys left because only strictly greater keys go right.
- If the search reaches null before finding a candidate, ceil returns null.
Algorithm code
JavaBinarySearchTree.javaStep linked
The highlighted line follows the current step.
Ready to begin
Press Play to see what happens.
Detailed execution
Snapshot 1 / 1
Comparisons 0