Payments app~30 min2s · 256 MBtarget O(n) time, O(n) spaceclassic twin: lc-106tree-recursion
A payments app sends a large transfer through a tree of approvers. Each approver has up to two reviewers below them, a left one and a right one. An audit export saved two lists of approver ids, each the order of a walk over the same tree.
The audit tool must rebuild the tree from the two lists. Every approver has a different id, and the tree can hold up to 200,000 approvers.
Write rebuild_approval_tree(inorder, postorder).
inorder lists the approver ids with each approver after the left subtree and before the right subtree.postorder lists the same ids with each approver after both of its subtrees.-1 for a missing child of an approver who 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: inorder = [3, 7, 9, 12, 20, 25], postorder = [3, 9, 7, 25, 20, 12]
Output: [12, 7, 20, 3, 9, -1, 25]The last id of the postorder list, 12, is the root. In the inorder list, 3, 7, 9 are on its left and 20, 25 on its right. In postorder, the right part comes right before the root, and the left part before that.
| Root (last of its stretch in postorder) | Piece of inorder | Left part | Right part |
|---|---|---|---|
| 12 | 3, 7, 9, 12, 20, 25 | 3, 7, 9 | 20, 25 |
| 20 | 20, 25 | none | 25 |
| 25 | 25 | none | none |
| 7 | 3, 7, 9 | 3 | 9 |
| 9 | 9 | none | none |
| 3 | 3 | none | none |
Input: inorder = [1, 2, 3], postorder = [3, 2, 1]
Output: [1, -1, 2, -1, 3]Postorder lists a right chain from the bottom up. Every left part is empty, so each child is a right child, and the -1 entries mark the missing left children.
Input: inorder = [], postorder = []
Output: []Two empty lists give the empty tree.
0 ≤ length of inorder ≤ 2 × 10^5postorder has the same length as inorder.1 ≤ inorder[i], postorder[i] ≤ 10^9On a chain of 200,000 approvers, finding each root in the inorder list by scanning costs about 20,000,100,000 steps. A lookup table makes each find one step.
The tree can 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.