Given a root node reference of a BST and a key, delete the node with the given key in the BST. Return the root node reference (possibly updated) of the BST.
Basically, the deletion can be divided into two stages:
Search for a node to remove.
If the node is found, delete the node.
Note: Time complexity should be O(height of tree).
Solution:
因為是BST,所以先利用二分查找到要刪除的node第队,若不是BST則需要依次找(Solution2)哮塞,找到node后的要刪除的幾種情況:
node doesn't have left or right - return null
node only has left subtree- return the left subtree
node only has right subtree- return the right subtree
-
node has both left and right - find the minimum value in the right subtree, 就是右樹的最左下node_lb,將其替換要刪除的node(替換連接)凳谦,并按照node_lb only has right subtree的方式刪除node_lb
Time Complexity: O(N) Space Complexity: O(1) (worst case O(n) for 遞歸緩存)
Solution1 Code:
class Solution {
private TreeNode deleteRootNode(TreeNode root) {
if (root == null) {
return null;
}
if (root.left == null) {
return root.right;
}
if (root.right == null) {
return root.left;
}
TreeNode next = root.right;
TreeNode pre = null;
for(; next.left != null; pre = next, next = next.left);
next.left = root.left;
if(root.right != next) {
pre.left = next.right;
next.right = root.right;
}
return next;
}
public TreeNode deleteNode(TreeNode root, int key) {
TreeNode cur = root;
TreeNode pre = null;
while(cur != null && cur.val != key) {
pre = cur;
if (key < cur.val) {
cur = cur.left;
} else if (key > cur.val) {
cur = cur.right;
}
}
if (pre == null) {
return deleteRootNode(cur);
}
if (pre.left == cur) {
pre.left = deleteRootNode(cur);
} else {
pre.right = deleteRootNode(cur);
}
return root;
}
}
**Solution2 Code: **
class Solution {
public:
TreeNode* deleteNode(TreeNode* root, int key) {
if (!root) return nullptr;
if (root->val == key) {
if (!root->right) {
TreeNode* left = root->left;
delete root;
return left;
}
else {
TreeNode* right = root->right;
while (right->left)
right = right->left;
swap(root->val, right->val);
}
}
root->left = deleteNode(root->left, key);
root->right = deleteNode(root->right, key);
return root;
}
};