Ad platform~20 min2s · 256 MBtarget O(n) time, O(n) spaceclassic twin: lc-669tree-recursion
An ad platform keeps campaign budgets in a search tree. A new policy removes every campaign whose budget is below low or above high. The remaining campaigns must stay in a valid search tree.
The tree can hold 100,000 campaigns. Your team lead wants the cut done in place, by changing links, and not by building a new tree.
Write trim_preorder(values, left, right, low, high).
0 to n - 1, and campaign 0 is the top of the tree. An empty tree has three empty lists.values[i] is the budget 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 budgets.low or above high. A removed campaign is replaced by what is left of its subtree. If its budget is below low, everything on its left is below low too, so its right side takes its place. If its budget is above high, its left side takes its place.Input: values = [8, 3, 10, 1, 6, 14, 4, 7, 13], left = [1, 3, -1, -1, 6, 8, -1, -1, -1], right = [2, 4, 5, -1, 7, -1, -1, -1, -1], low = 4, high = 10
Output: [8, 6, 4, 7, 10]With low = 4 and high = 10, the budgets 1, 3, 13 and 14 leave. The tree that remains has 8 on top, with 6 on its left (4 and 7 below it) and 10 on its right. Its preorder is [8, 6, 4, 7, 10].
| Phase | Fix | Ids that remain |
|---|---|---|
| [1] find the top | the top is 8, inside 4 to 10: nothing changes | [1, 3, 4, 6, 7, 8, 10, 13, 14] |
| [2] the left edge | the id 3 is below 4, so 8's left link goes to its right child 6 (ids [3, 1] leave) | [4, 6, 7, 8, 10, 13, 14] |
| [3] the right edge | the id 14 is above 10, and so is its left child 13: 10's right link becomes none (ids [14, 13] leave) | [4, 6, 7, 8, 10] |
Input: values = [7], left = [-1], right = [-1], low = 8, high = 9
Output: []Input: values = [], left = [], right = [], low = 3, high = 9
Output: []0 ≤ length of values = length of left = length of right ≤ 10^51 ≤ values[i] ≤ 10^9, and the budgets are distinctleft and right is -1 or a campaign number from 1 to n - 101 ≤ low ≤ high ≤ 10^9The campaigns can arrive in sorted order and form a chain of 100,000. Inserting the remaining campaigns one by one into a new tree then takes about n^2 / 2 steps.
Cut links in the tree you already have. Every node of the new tree was in the old tree, and each link is changed at most once.