Engineering platform~25 min2s · 256 MBtarget O(n) time, O(n) spaceclassic twin: lc-145tree-recursion · stacks
A platform runs services that depend on each other in a tree. Each service has a code, and up to two sub-services below it that depend on it. To shut the platform down safely, no service may stop before the sub-services below it have stopped.
The tree can hold 100,000 services, and a dependency chain can be very deep. The shutdown tool runs with a small call stack, so it cannot use recursion. Write the order in which the services stop.
Write postorder_walk(values, left, right).
0 to n - 1, and service 0 is the top of the tree. An empty tree has three empty lists.values[i] is the code of service i. left[i] and right[i] are the services below it, or -1 where there is none.Input: values = [30, 12, 25, 7, 9, 18, 4], left = [1, 3, 5, -1, -1, -1, -1], right = [2, 4, -1, -1, -1, 6, -1]
Output: [7, 9, 12, 4, 18, 25, 30]The tree has 30 at the top. Below it are 12 and 25. The service 12 has 7 on its left and 9 on its right. The service 25 has 18 on its left, and 18 has 4 on its right.
| Step | What happens | Stack (top at the right) | Written, in this order |
|---|---|---|---|
| [2], [3] | Pop 30, write it. Push 12 and then 25 | 12, 25 | 30 |
| [2], [3] | Pop 25, write it. Push 18 | 12, 18 | 30, 25 |
| [2], [3] | Pop 18, write it. Push 4 | 12, 4 | 30, 25, 18 |
| [2] | Pop 4 and write it | 12 | 30, 25, 18, 4 |
| [2], [3] | Pop 12, write it. Push 7 and then 9 | 7, 9 | ..., 12 |
| [2] | Pop 9 and then 7 | 30, 25, 18, 4, 12, 9, 7 | |
| [4] | Reverse the written list | 7, 9, 12, 4, 18, 25, 30 |
Input: values = [7], left = [-1], right = [-1]
Output: [7]A single service stops alone.
Input: values = [], left = [], right = []
Output: []An empty tree gives an empty list.
0 ≤ n ≤ 100,000 and 1 ≤ values[i] ≤ 10^9left and right is -1 or a service number from 1 to n - 10A chain of 100,000 services needs 100,000 nested calls if each call handles a service and its sides. Many tools allow far fewer.
A stack of your own, plus one reversal at the end, visits every service twice. That is about 300,000 steps, however deep the tree is.