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.
删除二叉搜索树中指定的节点。
思路:
二叉搜索树删除节点有几种情况。
(1) root是null时直接返回null
(2) root.val < key,那么key在右子树,那么只需要把root.right和key传入,递归处理删除二叉搜索树节点即可。
(3) root.val > key, 同样的,key在左子树,只需要把root.left和key传入,递归处理删除二叉搜索树节点即可。
(4) root.val == key
这时又分几种情况(就不画图了)
1 当前root是叶子节点,直接删除该点即可,即root=null,返回root
(可以并到2,3情况)
2 当前节点没有左子树,那么直接把它的右子树接到parent,再把该节点删除。即返回右子树的根节点,删除当前节点
3 当前节点没有右子树,那么直接把它的左子树接到parent,再把该节点删除。即返回左子树的根节点,删除当前节点
4 当前root节点既有左子树又有右子树,这时候要在右子树中找到最小的点node,node.val替换到root里,再把原node点删掉,而把原node删掉这步只需要传入右子树根节点和node.val,递归调用即可(代码中用这种方法)。
或者复杂一点,变动指针把node和root点替换后删除原node点。
总结一下就是以下几种情况
1 root是null,直接返回null即可
2 key和root.val不相等,那么递归调用在左子树或右子树中找key并删除
3 key和root.val相等,这时要看root有没有左右子树,如果有一个或都没有,直接删除节点。如果有左右子树,就找到右子树中最小值的节点替换到root,并删除替换到右子树中最小值处的节点。
public TreeNode deleteNode(TreeNode root, int key) {
if(root == null) return root;
if(root.val < key){
root.right = deleteNode(root.right, key);
} else if(root.val > key) {
root.left = deleteNode(root.left, key);
} else {
TreeNode newRoot = null;
if(root.left == null) {
newRoot = root.right;
root = null;
return newRoot;
} else if(root.right == null) {
newRoot = root.left;
root = null;
return newRoot;
} else {
newRoot = root.right;
while(newRoot.left != null) {
newRoot = newRoot.left;
}
root.val = newRoot.val;
root.right = deleteNode(root.right, newRoot.val);
}
}
return root;
}