Trees & Ordered Maps Hard
BST Reconstruction from Pre-Order
A valid preorder sequence contains enough information to rebuild its unique-key binary search tree in one linear recursive pass.
Trace input
Bounded JSONEdit the lesson input, then build a deterministic source-linked trace.
Source scenarios
Complexity
BestO(N)
AverageO(N)
WorstO(N)
SpaceO(H) recursive stack plus O(N) output nodes
Array state
Follow the active comparisons and writes.
Current operation
Trace stateReady to explore
Source behavior & common mistakes
Read each candidate under its allowed key range. Recurse into the left range first, then use that subtree's stored size to jump to the right subtree in the preorder array.
- The source assumes a valid preorder emitted by put/preorderWrite, so duplicates and impossible subtree orderings are rejected at validation.
- A candidate outside its current inclusive range returns null without consuming the preorder position; its caller may try that same position in the right subtree.
- The right subtree begins at i + 1 + leftSize, not at a guessed key comparison or by rescanning the left subtree.
- The Java bounds use Integer.MIN_VALUE and Integer.MAX_VALUE inclusively, so both signed 32-bit extreme keys are valid.
- The source recursively explores both children; a sorted input forms a deep chain even though the work remains linear.
Algorithm code
JavaPreorderToBST.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 · Writes 0