public TreeNode deleteNode(TreeNode root, int key) {
if (root == null) return null;
if (key < root.val) root.left = deleteNode(root.left, key);
else if (key > root.val) root.right = deleteNode(root.right, key);
else {
if (root.left == null) return root.right;
else if (root.right == null) return root.left;
// TreeNode minNode = sucessor(root);
root.val = successorVal(root);
root.right = deleteNode(root.right, root.val);
}
return root;
}
public int successorVal(TreeNode root) {
root = root.right;
while (root.left != null)
root = root.left;
return root.val;
}
public int successor(TreeNode root) {
root = root.right;
while (root.left != null)
root = root.left;
return root.val;
}
public int predecessor(TreeNode root) {
root = root.left;
while (root.right != null)
root = root.right;
return root.val;
}
public TreeNode deleteNode(TreeNode root, int key) {
if (root == null) return null;
if (key > root.val) root.right = deleteNode(root.right, key);
else if (key < root.val) root.left = deleteNode(root.left, key);
else {
if (root.left == null && root.right == null) root = null;
else if (root.right != null) {
root.val = successor(root);
root.right = deleteNode(root.right, root.val);
} else {
root.val = predecessor(root);
root.left = deleteNode(root.left, root.val);
}
}
return root;
}
450. Delete Node in a BST
最新推荐文章于 2021-03-30 11:07:04 发布