Update a Key in a BST
You are given an array keys of distinct integers. Starting with an empty binary search tree, insert the values of keys from left to right.
You are also given a matrix updates, where updates[i] = [old, new]. Process the rows in order:
- If old is not in the tree, record NOT FOUND and leave the tree unchanged.
- Otherwise, if old equals new, leave the tree unchanged and record no message.
- Otherwise, if new is already in the tree, record EXISTS and leave the tree unchanged.
- Otherwise, delete old. When the deleted node has two children, replace it with its inorder successor. Then insert new by searching from the root. A successful update records no message.
Return one string. Each rejected update contributes exactly one NOT FOUND or EXISTS segment in update order. After those segments, append INORDER: followed by the inorder values, then PREORDER: followed by the preorder values.
Join every segment with space, vertical bar, space. Separate values inside each traversal with one space. If no update records a message, the string begins directly with INORDER:.
Example 1:
Input: keys = [5, 3, 7, 2, 4, 6, 8], updates = [[5, 9], [42, 1], [3, 8], [6, 6]]
Output: NOT FOUND | EXISTS | INORDER: 2 3 4 6 7 8 9 | PREORDER: 6 3 2 4 7 8 9
Explanation: Replacing 5 with 9 succeeds. The update [42, 1] records NOT FOUND, [3, 8] records EXISTS, and [6, 6] changes nothing. Deleting 5 uses its inorder successor 6, which becomes the root before 9 is inserted.
Example 2:
Input: keys = [10, 5, 15], updates = [[5, 12], [10, 20], [15, 12]]
Output: EXISTS | INORDER: 12 15 20 | PREORDER: 15 12 20
Explanation: The first two updates succeed. The final update records EXISTS because 12 is already present, so the final root remains 15.
Now Your Turn!
Pick the correct output for the given inputInput: keys = [8, 4, 12, 2, 6, 10, 14], updates = [[4, 5], [12, 10], [99, 1], [5, 5]]
Still unsure what the problem is asking ?
Let’s go through a few more examples, step by step, to make it clearer.
Constraints:
- 1 <= keys.length <= 200000
- 1 <= updates.length <= 200000
- keys.length + updates.length <= 200000
- -109 <= keys[i] <= 109
- All values in keys are distinct.
- updates[i].length = 2
- -109 <= updates[i][j] <= 109
- After inserting any prefix of keys, and after every successful update, the BST height is at most 64.