Trains the technique from
LeetCode 1008Construct Binary Search Tree from Preorder TraversalThis is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.
Same function shape, different story and different numbers.
A museum files its specimens in a branching index. Each card in the index carries one accession number and hangs at most two cards below it, one on the low side and one on the high side. The filing rule holds everywhere in the index: every number hanging anywhere below a card on its low side is smaller than that card's number, and every number hanging anywhere below it on its high side is larger. All the numbers are different.
A curator read the index out into entries in card-first order: she wrote down a card's number, then the whole of what hangs on its low side, then the whole of what hangs on its high side, applying that same order at every card she reached. entries[0] is therefore the topmost card.
Rebuild the index and return it as a band listing, one band of the index at a time from the top down, left to right within a band. Slot 0 holds the topmost card. Each card that appears in the listing takes the next two unclaimed slots for what hangs below it, the low side first and the high side second. A slot holding null means nothing hangs there, and such a slot claims no slots of its own. Slots that would hold null at the very end of the listing must be left off.
Exactly one index matches a given card-first reading, so the listing is unique.
Example 1
The topmost card is 9. The reading covers all of its low side next, namely 4 with 2 below on the low side and 6 below on the high side, and only then its high side, namely 15 with 20 hanging high of it.
Example 2
Each number read is smaller than the one before it, so every card hangs on the low side of the card just read, and the index is a single chain down the low side.
Example 3
One card and nothing hanging below it, so the listing has a single slot.
Example 4
The index comes out full to three bands: 50 on top, then 30 and 70, then 20, 40, 60 and 80.
Example 5
Card 2 has 1 on its low side and nothing on its high side, so the slot for that high side sits in the middle of the listing holding `null`.
The editor is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.
def bst_from_preorder(entries: list[int]) -> list[int | None]:public Integer[] bstFromPreorder(int[] entries)See the step-by-step animation, the intuition, and clean code in every language — free, no credit card.