Bank app~25 min2s · 256 MBtarget O(n) time, O(n) spaceclassic twin: lc-450tree-recursion
A bank app keeps its account numbers in a search tree. When an account is closed, its number must leave the tree, and the rest must stay a valid search tree.
The tree can hold 100,000 accounts. Your team lead wants the removal done by changing links, and the same rule used every time, so that two copies of the tree stay identical.
Write delete_preorder(values, left, right, key).
0 to n - 1, and account 0 is the top of the tree. An empty tree has three empty lists.values[i] is the account number of account i. left[i] and right[i] are the accounts on its left and right, or -1 where there is none. The tree is a search tree with distinct numbers.key. If there is none, change nothing.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], key = 3
Output: [8, 4, 1, 6, 7, 10, 14, 13]The account 3 has two children, so it takes its successor's number, 4, and the old node of 4 is removed. The preorder was [8, 3, 1, 6, 4, 7, 10, 14, 13] and becomes [8, 4, 1, 6, 7, 10, 14, 13].
| Step | What happens | Ids in preorder |
|---|---|---|
| Before | the id 3 has two children, 1 and 6 | [8, 3, 1, 6, 4, 7, 10, 14, 13] |
| [2] | the successor is the smallest id on the right side of 3: from 6 go left to 4 | |
| [3] | the node of 3 now holds 4, and the old node of 4 is unlinked (its right child, none, takes its place) | |
| [5] | walk the result in preorder | [8, 4, 1, 6, 7, 10, 14, 13] |
Input: values = [5], left = [-1], right = [-1], key = 5
Output: []Input: values = [8, 3, 10], left = [1, -1, -1], right = [2, -1, -1], key = 4
Output: [8, 3, 10]0 ≤ length of values = length of left = length of right ≤ 10^51 ≤ values[i] ≤ 10^9, and the numbers are distinctleft and right is -1 or an account number from 1 to n - 101 ≤ key ≤ 10^9Accounts can arrive in sorted order, so the tree can be a chain of 100,000. Rebuilding the tree by inserting every other account then costs about n^2 / 2 steps.
Finding the account and its successor follows one path each, so the change to the links costs about the height. Only the final walk that lists the result reads every account.