Ride-hailing app~30 min2s · 256 MBtarget O(n) time, O(n) spaceclassic twin: lc-105tree-recursion
A ride-hailing app groups its pick-up zones in a tree: a city has districts, and a district has blocks. An export job did not save the tree itself. It saved two lists of zone ids, each the order of a walk over the same tree.
The import job must rebuild the tree from these two lists. Every zone has a different id, and the tree can hold up to 200,000 zones.
Write rebuild_zone_tree(preorder, inorder).
preorder lists the zone ids with each zone before its left subtree and its right subtree.inorder lists the same ids with each zone after its left subtree and before its right subtree.-1 for a missing child of a zone 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 both lists are empty.Input: preorder = [5, 2, 9, 4, 7, 3], inorder = [9, 2, 4, 5, 3, 7]
Output: [5, 2, 7, 9, 4, 3]The first id of the preorder list, 5, is the root. In the inorder list it sits after 9, 2, 4, so those three ids are its left subtree. The ids after it, 3 and 7, are the right subtree. Each part is split the same way.
| Root (next in preorder) | Piece of inorder | Left part | Right part |
|---|---|---|---|
| 5 | 9, 2, 4, 5, 3, 7 | 9, 2, 4 | 3, 7 |
| 2 | 9, 2, 4 | 9 | 4 |
| 9 | 9 | none | none |
| 4 | 4 | none | none |
| 7 | 3, 7 | 3 | none |
| 3 | 3 | none | none |
Input: preorder = [1, 2, 3], inorder = [1, 2, 3]
Output: [1, -1, 2, -1, 3]Every zone has an empty left part, so each child is a right child. The -1 entries mark the missing left children. The last one is dropped.
Input: preorder = [], inorder = []
Output: []Two empty lists give the empty tree.
0 ≤ length of preorder ≤ 2 × 10^5inorder has the same length as preorder.1 ≤ preorder[i], inorder[i] ≤ 10^9On a chain of 200,000 zones, finding each root in the inorder list by scanning costs about 20,000,100,000 steps in all. A lookup table makes each find one step.
The tree can also be 200,000 levels deep. A function that calls itself for each part raises a RecursionError in Python, and risks a stack overflow in Java and C++. Keep the waiting parts on a stack that you manage.