二叉搜索树BST常用操作
BST逻辑代码
void BST(TreeNode root, int target) {
if (root.val == target)
// 找到目标,做点什么
if (root.val < target)
BST(root.right, target);
if (root.val > target)
BST(root.left, target);
}
(1)判断BST合法性
boolean isValidBST(TreeNode root){
return isVaildBST(root,null,null);
}
boolean iusValidBST(TreeNode root,TreeNode min,TreeNode max){
// base case
if(root == null) return true;
// 如果 root.val 不符合 max 和 min 的限制,说明不是BST
if(min != null && root.val <= min.val) return false;
if(max != null && root.val >= max.val) return false;
// 限定左子树的最大值是 root.val,右子树的最小值是 root.val
return isValidBST(root.left,min,root) && isValidBST(root.right,root,max);
}
(2)在BST中搜索元素
TreeNode searchBST(TreeNode root,int target){
if(root == null){
return null;
}
// 去左子树搜索
if(root.val > target){
return searchBST(root.left,target);
}
// 去右子树搜索
if(root.val < target){
return searchBST(root.right,target);
}
return root;
}
(3)在BST中插入元素
TreeNode insertIntoBST(TreeNode root,int val){
// 找到空位置插入新节点
if(root == null) return new TreeNode(val);
// if (root.val == val)
// BST 中一般不会插入已存在元素
if(root.val < val){
root.right = insertIntoBST(root.right,val);
}
if(root.val > val){
root.left = insertIntoBST(root,left,val);
}
return root;
}
(4)在BST中删除元素
情况 1:A
恰好是末端节点,两个子节点都为空,那么它可以当场去世了。
if (root.left == null && root.right == null)
return null;
情况 2:A
只有一个非空子节点,那么它要让这个孩子接替自己的位置。
// 排除了情况 1 之后
if (root.left == null) return root.right;
if (root.right == null) return root.left;
情况 3:A
有两个子节点,麻烦了,为了不破坏 BST 的性质,A
必须找到左子树中最大的那个节点,或者右子树中最小的那个节点来接替自己。我们用第二种方式。
if (root.left != null && root.right != null) {
// 找到右子树的最小节点
TreeNode minNode = getMin(root.right);
// 把 root 改成 minNode
root.val = minNode.val;
// 转而去删除 minNode
root.right = deleteNode(root.right, minNode.val);
}
代码如下:
TreeNode deleteNode(TreeNode root, int key) {
if (root == null) return null;
if (root.val == key) {
// 这两个 if 把情况 1 和 2 都正确处理了
if (root.left == null) return root.right;
if (root.right == null) return root.left;
// 处理情况 3
// 获得右子树最小的节点
TreeNode minNode = getMin(root.right);
// 删除右子树最小的节点
root.right = deleteNode(root.right, minNode.val);
// 用右子树最小的节点替换 root 节点
minNode.left = root.left;
minNode.right = root.right;
root = minNode;
} else if (root.val > key) {
root.left = deleteNode(root.left, key);
} else if (root.val < key) {
root.right = deleteNode(root.right, key);
}
return root;
}
TreeNode getMin(TreeNode node) {
// BST 最左边的就是最小的
while (node.left != null) node = node.left;
return node;
}
注:我们一般不会通过修改节点内部的值来交换节点。因为在实际应用中,BST 节点内部的数据域是用户自定义的,可以非常复杂,而 BST 作为数据结构(一个工具人),其操作应该和内部存储的数据域解耦,所以我们更倾向于使用指针操作来交换节点,根本没必要关心内部数据。