#BST0000019. Xóa nút trong BST (Delete Node in a BST)
Xóa nút trong BST (Delete Node in a BST)
Delete Node in a BST
Source: LeetCode
Version: Phuoc Hung OJ Extended
Problem Statement
Build a BST by inserting the distinct keys in the given order. Then delete key.
If key is absent, leave the tree unchanged. If the node exists:
- remove it directly if it has no child;
- replace it by its only child if it has exactly one child;
- if it has two children, replace it by its inorder successor, the node with the smallest key in its right subtree, then remove that successor from its old position.
The successor rule in the two-child case makes the resulting tree unique in this version.
Print the preorder traversal after the operation.
Input
The first line contains .
If , the next line contains the distinct keys . If , this line is absent.
The last line contains key.
Output
If the resulting tree is non-empty, print its preorder keys separated by one space.
If the tree is empty, print EMPTY.
Subtasks
Subtask 1 (20 points): .
Subtask 2 (30 points): .
Subtask 3 (50 points): .
In all subtasks, the tree keys are distinct and .
Examples
Input
7
5 3 6 2 4 7 1
3
Output
5 4 2 1 6 7
Explanation
Node has two children. The minimum key in its right subtree is , so is its inorder successor.
Replace by and remove the old node . The resulting preorder is 5 4 2 1 6 7.