二分搜索树的定义为:
(1)所有左子树中的结点小于等于根节点
(2)所有右子树中的结点大于等于根节点
(3)其任意子树也满足(1), (2)
(注意是所有结点)
二分搜索树删除结点
主要可以分为以下三种情况:
(1)被删除的结点为叶子结点:直接将其置为空即可;
(2)被删除的结点只有左孩子或右孩子,用其左孩子或右孩子替代即可;
(3)被删除的结点左右孩子都不为空:可以采取两种做法:
a. 寻找其左子树中的最大值,并将当前结点替换为该值,递归在左子树中删除该值;
b. 寻找其右子树中的最小值,并将当前结点替换为该值,递归在右子树中删除该值;
代码实现
class Solution {
public TreeNode deleteNode(TreeNode root, int key) {
if(root == null) return root;
if(key < root.val) {
root.left = deleteNode(root.left, key);
return root;
}
if(key > root.val) {
root.right = deleteNode(root.right, key);
return root;
}
//1.该结点为叶子结点,直接删除
if(root.left == null && root.right == null) {
root = null;
return root;
}
//2.该结点右孩子为空(左孩子替代)
if(root.left != null && root.right == null) {
root = root.left;
return root;
}
//3.该结点左孩子为空(右孩子替代)
if(root.right != null && root.left == null) {
root = root.right;
return root;
}
//4.左右孩子都不为空(挑选左子树中最大的或者右子树中最小的,替换当前节点)
if(root.left != null && root.right != null) {
int val = findMaxLeft(root.left);
root.val = val;
root.left = deleteNode(root.left, val);
return root;
}
return root;
}
//寻找以node为根结点的最大值
private int findMaxLeft(TreeNode node) {
if(node == null) return 0;
if(node.left == null && node.right == null) return node.val;
if(node.right == null) {
return node.val;
}
return findMaxLeft(node.right);
}
}
参考:
LeetCode 450. Delete Node in a BST
https://blog.csdn.net/xiaoxiaoxuanao/article/details/61918125