Ad platform~20 min2s · 256 MBtarget O(n) time, O(n) spaceclassic twin: lc-107bfs
An ad platform organises a campaign as a tree. Each account of the tree is an ad group with a budget code, and it has at most two smaller ad groups directly below it. The top is the whole campaign.
A nightly report adds up the budgets from the bottom. It needs the codes level by level, starting with the lowest level and ending with the top. The tree can have 100,000 ad groups, and it can be very deep.
Write levels_bottom_up(values, left, right).
0 to n - 1, and account 0 is the top of the tree. An empty tree has three empty lists.values[i] is the budget code of account i. left[i] and right[i] are the accounts below it, or -1 where there is none.Input: values = [12, 5, 9, 3, 7, 11, 2], left = [1, 3, -1, 6, -1, -1, -1], right = [2, 4, 5, -1, -1, -1, -1]
Output: [[2], [3, 7, 11], [5, 9], [12]]The tree has 12 at the top, then 5 and 9, then 3, 7 and 11, and the code 2 below 3.
| Step | What happens | Levels found, from the top |
|---|---|---|
| [1] | The first level is the top account | |
| [2] | Write down level 0 | [[12]] |
| [3], [2] | The children are 5 and 9. Write down level 1 | [[12], [5, 9]] |
| [3], [2] | The children are 3, 7 and 11. Write down level 2 | [[12], [5, 9], [3, 7, 11]] |
| [3], [2] | The only child is 2. Write down level 3 | [[12], [5, 9], [3, 7, 11], [2]] |
| [4] | Reverse the order of the levels | [[2], [3, 7, 11], [5, 9], [12]] |
Input: values = [4], left = [-1], right = [-1]
Output: [[4]]A single account is one level.
Input: values = [], left = [], right = []
Output: []An empty tree has no level, so the answer is an empty list.
0 ≤ n ≤ 100,000 and 1 ≤ values[i] ≤ 10^9left and right is -1 or an account number from 1 to n - 10A tree of 100,000 accounts can have 100,000 levels. Collecting each level with a new walk of the whole tree would cost up to 100,000 × 100,000 = 10 billion steps.
One pass that builds the levels from the top down visits each account once, so it takes about 100,000 steps. Reversing the list of levels adds one more pass over the levels.