Music streaming app~20 min2s · 256 MBtarget O(n) time, O(h) spaceclassic twin: lc-94tree-recursion
A video app keeps its categories in a binary tree. Each category has a code, and up to two sub-categories below it. The catalogue editor wants a flat list: for each category, the categories on its left first, then the category itself, then the categories on its right.
The tree can hold 100,000 categories, and editors sometimes build it as one very long chain. A solution must list it without running out of call stack.
Write inorder_walk(values, left, right).
0 to n - 1, and category 0 is the top of the tree. An empty tree has three empty lists.values[i] is the code of category i. left[i] and right[i] are the categories below it, or -1 where there is none.Input: values = [40, 15, 60, 8, 22, 51, 75, 30], left = [1, 3, 5, -1, 7, -1, -1, -1], right = [2, 4, 6, -1, -1, -1, -1, -1]
Output: [8, 15, 30, 22, 40, 51, 60, 75]The tree has 40 at the top. Below it are 15 and 60. The category 15 has 8 on its left and 22 on its right, and 22 has 30 on its left.
| Step | What happens | Stack (top at the right) | Written |
|---|---|---|---|
| [2] | Go left from 40: push 40, 15, 8 | 40, 15, 8 | |
| [3] | Pop 8, write it. It has no right child | 40, 15 | 8 |
| [3] | Pop 15, write it, go right to 22 | 40 | 8, 15 |
| [2] | Go left from 22: push 22, 30 | 40, 22, 30 | 8, 15 |
| [3] | Pop 30, then pop 22, then pop 40, writing each | 8, 15, 30, 22, 40 | |
| [2], [3] | Go right to 60, left to 51, write 51, then 60, then 75 | 8, 15, 30, 22, 40, 51, 60, 75 |
Input: values = [7], left = [-1], right = [-1]
Output: [7]A single category is listed alone.
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 category number from 1 to n - 10A tree of 100,000 categories can be a chain, 100,000 deep. A function that calls itself for each category then needs 100,000 calls on the stack, and many languages stop long before that.
A loop with a stack of your own keeps the waiting categories in memory you control. Each category is pushed once and popped once, so the walk takes about 200,000 steps.