Music streaming app~30 min2s · 256 MBtarget O(n) time, O(n) spaceclassic twin: lc-1008tree-recursion
A music streaming app keeps its track ids in a binary search tree, so that it can look up a track quickly. For a backup, the tree was saved as one list: the order in which a preorder walk visits the tracks.
The restore job must rebuild the same tree from this list alone. Every track id is different, and the tree can hold up to 100,000 tracks.
Write rebuild_catalogue_index(preorder).
preorder lists the track ids of a binary search tree, each node before its left subtree and its right subtree. In a search tree, every id in the left subtree of a node is smaller than the node, and every id in the right subtree is larger.-1 for a missing child of a node that is in the tree. A missing child has no children, so nothing follows it. Drop every -1 at the end of the list.[] when preorder is empty.Input: preorder = [8, 5, 1, 7, 10, 12]
Output: [8, 5, 10, 1, 7, -1, 12]The first id, 8, is the root. The ids 5, 1 and 7 are smaller, so they form the left part. The ids 10 and 12 are larger, so they form the right part. The table shows how a stack finds this split in one pass.
| Value | Stack of waiting nodes (values) | Removed, in order | Attached as |
|---|---|---|---|
| 8 | - | - | the root |
| 5 | 8 | none | left child of 8 |
| 1 | 8, 5 | none | left child of 5 |
| 7 | 8, 5, 1 | 1, 5 | right child of 5 |
| 10 | 8, 7 | 7, 8 | right child of 8 |
| 12 | 10 | 10 | right child of 10 |
Input: preorder = [1, 2, 3]
Output: [1, -1, 2, -1, 3]Each id is larger than the one before, so each is a right child. The -1 entries mark the missing left children, and the last one is dropped.
Input: preorder = []
Output: []An empty list is the empty tree.
0 ≤ length of preorder ≤ 10^51 ≤ preorder[i] ≤ 10^6preorder is the preorder walk of a binary search tree.Inserting the ids one by one costs the depth of the tree for each id. On a chain of 100,000 tracks that adds up to 4,999,950,000 steps. A stack finds each place in one amortised step.
The tree can be 100,000 levels deep. A function that calls itself for each subtree raises a RecursionError in Python, and risks a stack overflow in Java and C++.