Ad platform~25 min2s · 256 MBtarget O(k × h + n) time, O(n + k) spaceclassic twin: lc-701tree-recursion
An ad server keeps the ids of the campaigns it runs in a search tree. When new campaigns launch, their ids must be added so that the tree stays a search tree. A campaign id that is already in the tree is not added again.
The server adds a few campaigns at a time, and the tree can hold 30,000 ids. Adding an id must not rebuild the tree, because the server reads the tree while it picks ads.
Write insert_preorder(values, left, right, keys).
0 to n - 1, and campaign 0 is the top of the tree. An empty tree has three empty lists.values[i] is the id of campaign i. left[i] and right[i] are the campaigns on its left and right, or -1 where there is none. The tree is a search tree with distinct ids.keys one after another, in order. An id is added as a new leaf at the place where a lookup for it ends. If the id is already in the tree, change nothing.Input: values = [50, 30, 70, 20, 40, 60, 80, 35], left = [1, 3, 5, -1, 7, -1, -1, -1], right = [2, 4, 6, -1, -1, -1, -1, -1], keys = [45, 65, 10]
Output: [50, 30, 20, 10, 40, 35, 45, 70, 60, 65, 80]| Step | What happens | New place |
|---|---|---|
| [2], [3] | Add 45: 50 left to 30, right to 40, right of 40 is empty | right of 40 |
| [2], [3] | Add 65: 50 right to 70, left to 60, right of 60 is empty | right of 60 |
| [2], [3] | Add 10: 50 left to 30, left to 20, left of 20 is empty | left of 20 |
| [4] | Walk the new tree in preorder | [50, 30, 20, 10, 40, 35, 45, 70, 60, 65, 80] |
Input: values = [50, 30, 70, 20, 40, 60, 80, 35], left = [1, 3, 5, -1, 7, -1, -1, -1], right = [2, 4, 6, -1, -1, -1, -1, -1], keys = [30, 80]
Output: [50, 30, 20, 40, 35, 70, 60, 80]Both ids are already in the tree, so the tree does not change.
Input: values = [], left = [], right = [], keys = [8, 3, 12, 3]
Output: [8, 3, 12]The first id becomes the top, then 3 goes left and 12 goes right. The second 3 is already there.
0 ≤ n ≤ 30,000 and 0 ≤ len(keys) ≤ 301 ≤ values[i], keys[j] ≤ 10^9, and the ids in the tree are distinctleft and right is -1 or a campaign number from 1 to n - 10Ids may arrive in sorted order, so the tree can be a chain of 30,000. An insertion then walks up to 30,000 steps, and 30 insertions take under a million steps.
Rebuilding the whole tree for every change would repeat all those walks. For a chain that is about 30,000 × 30,000 / 2 = 450 million steps.