Monitoring~30 min2s · 256 MBtarget O(n) time, O(n) spaceclassic twin: lc-114tree-recursion
A monitoring system records a traced request as a tree of calls. Each call has a left sub-call and a right sub-call, and the left one starts first. The trace can hold up to 200,000 calls.
The report page wants a plain list of the calls in the order they started, linked one after another through the right link. Your team lead asks: "Rewire the links of the tree. Do not build a second tree."
Write flatten_call_trace(left, right).
0 to n - 1. Call 0 is the first call, the root. left[i] and right[i] are the sub-calls of call i, or -1 where there is none.right list: for each call, the number of the call that starts next, or -1 for the last one. Return [] when n is 0.Input: left = [1, 3, -1, -1, -1, -1], right = [2, 4, 5, -1, -1, -1]
Output: [1, 3, 5, 4, 2, -1]The order of the calls is 0, 1, 3, 4, 2, 5. Call 0 has the left part 1, 3, 4 and the right part 2, 5. The last call of the left part is 4, so the right part is hung on call 4.
| Call (node) | Last node of its left part | Old right part | Next call after it |
|---|---|---|---|
| 0 | 4 | 2 | 1 |
| 1 | 3 | 4 | 3 |
| 3 | none | none | 4 |
| 4 | none | none | 2 |
| 2 | none | none | 5 |
| 5 | none | none | none |
Input: left = [-1, -1, -1], right = [1, 2, -1]
Output: [1, 2, -1]Every call already has only a right link, so nothing changes.
Input: left = [], right = []
Output: []An empty trace gives an empty list.
0 ≤ length of left ≤ 2 × 10^5right has the same length as left.-1 ≤ left[i], right[i] < n, and the links form a binary tree rooted at call 0.A trace can be a chain of 200,000 calls that all go left. A function that calls itself for each call raises a RecursionError in Python, and risks a stack overflow in Java and C++. Rewire the links in a loop instead.
If you walk to the end of the flattened left chain at every call, the walks add up to 19,999,900,000 steps on that chain. Walking the left part before it is flattened costs far less.