Maps app~25 min2s · 256 MBtarget O(n) time, O(h) spaceclassic twin: lc-144tree-recursion · stacks
A map app stores its regions in a binary tree. Each region has a code, and up to two smaller regions inside it. The app exports an indented outline: each region comes before the regions inside it, and the export also gives its depth, so that the outline can be indented.
The tree can hold 100,000 regions, and some trees are very deep. The export must not use recursion, because the export servers have a small call stack.
Write preorder_outline(values, left, right).
0 to n - 1, and region 0 is the top of the tree. An empty tree has three empty lists.values[i] is the code of region i. left[i] and right[i] are the regions inside it, or -1 where there is none.[code, depth] for each region, in preorder: a region, then everything on its left side, then everything on its right side.Input: values = [10, 4, 9, 7, 2, 6, 8], left = [1, 3, -1, -1, -1, 6, -1], right = [2, 4, 5, -1, -1, -1, -1]
Output: [[10, 0], [4, 1], [7, 2], [2, 2], [9, 1], [6, 2], [8, 3]]The tree has 10 at the top. Inside it are 4 and 9. The region 4 holds 7 and 2. The region 9 holds 6 on its right, and 6 holds 8 on its left.
| Step | What happens | Stack of (code, depth), top at the right |
|---|---|---|
| [1] | Start with the top | (10, 0) |
| [2], [3] | Write 10. Push 9 then 4 | (9, 1), (4, 1) |
| [2], [3] | Write 4. Push 2 then 7 | (9, 1), (2, 2), (7, 2) |
| [2] | Write 7 and then 2: both are leaves | (9, 1) |
| [2], [3] | Write 9. Push 6 | (6, 2) |
| [2], [3] | Write 6. Push 8 | (8, 3) |
| [2] | Write 8 |
The left side of every region is written before its right side, because the left child is pushed last and so it is on top.
Input: values = [7], left = [-1], right = [-1]
Output: [[7, 0]]A single region is the top, at depth 0.
Input: values = [], left = [], right = []
Output: []An empty tree gives an empty list.
0 ≤ n ≤ 100,000 and 1 ≤ values[i] ≤ 10^6left and right is -1 or a region number from 1 to n - 10A tree of 100,000 regions can be a chain 100,000 deep. A recursive walk then needs 100,000 nested calls, which is more than many servers allow.
A stack of your own holds the waiting regions in a list. Each region is pushed once and popped once, so the walk takes about 200,000 steps.