Trees & Ordered Maps Medium
BST Higher-Key Query
This unbalanced binary search tree stores unique comparable keys, tracks subtree sizes, and recursively searches for the strict successor of a target.
Trace input
Bounded JSONEdit the lesson input, then build a deterministic source-linked trace.
Source scenarios
Complexity
BestO(h) per insertion or query
AverageO(log N) in a balanced shape
WorstO(N) for a chain-shaped tree
SpaceO(h) recursive call stack
Array state
Follow the active comparisons and writes.
Current operation
Trace stateReady to explore
Source behavior & common mistakes
Insert the keys in order, find minKey by following left children, then find higherKey: the least stored key strictly greater than the query. An equal key is never its own successor.
- higherKey is strict: a target equal to a stored key continues to the right subtree.
- When target < x.key, the algorithm searches left first because that subtree may contain a closer greater key; x.key is the fallback only when left returns null.
- This implementation is an ordinary, unbalanced BST; insertion order determines its shape and recursion depth.
- Putting a duplicate key updates the existing node value and recalculates subtree sizes without allocating a new node.
- Integer key comparisons use compareTo and do not subtract keys, so signed 32-bit extremes compare safely.
- minKey returns null on an empty tree; higherKey returns null when no key is strictly greater than the target.
Algorithm code
JavaBinarySearchTreeHigher.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