东哥带你刷二叉搜索树(基操篇)
基于labuladong的算法网站,东哥带你刷二叉搜索树(基操篇)
1、判断BST的合法性
力扣第98题,验证二叉搜索树
[98]验证二叉搜索树
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public boolean isValidBST(TreeNode root) {
return isBST(root, null, null);
}
// 利用递归遍历,以node为根节点的必须为左小右大,用max和min保存头节点的约束
public boolean isBST(TreeNode node, TreeNode max, TreeNode min) {
if (node == null) {
return true;
}
// 该节点不满足条件
if (min != null && node.val <= min.val) {
return false;
}
if (max != null && node.val >= max.val) {
return false;
}
return isBST(node.left, node, min) && isBST(node.right, max, node);
}
}
采用递归遍历加上记录之前的约束条件,向左子树递归时候,需要注意的是传递最大值,向右子树递归时候,传递的则为最小值。保证左子树的最大值即为根节点,右子树的最小值即为根节点。
2、在BST中搜索元素
力扣第700题,二叉搜索树中的搜索
[700]二叉搜索树中的搜索
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public TreeNode searchBST(TreeNode root, int val) {
return find(root, val);
}
// 递归找
TreeNode find(TreeNode root, int val) {
// base case
if (root == null) {
return null;
}
// 判断该节点和整数值的关系
if (root.val == val) {
return root;
} else if (val < root.val) {
return find(root.left, val);
} else {
return find(root.right, val);
}
}
}
3、在BST中插入一个数
// 在BST中插入一个数,在根节点为root的二叉平衡树中插入值的value的节点
// 假设value的值不为二叉树中已经存在的值
// 返回插入节点后的二叉树的根节点
TreeNode insert(TreeNode root, int value) {
// 如果根节点为空,直接新建节点并返回
if (root == null) {
return new TreeNode(value);
}
// 比较value和根节点的大小
if (value < root.val) {
root.left = insert(root.left, value);
}
if (value > root.val) {
root.right = insert(root.right, value);
}
return root;// 返回根节点
}
4、在BST中删除一个数
// 在BST中删除一个数
// 以root为根节点的BST,删除值等于value的节点,并让删除该节点后的二叉树为BST,返回头节点
TreeNode delete(TreeNode root, int value) {
// 找不到
if (root == null) {
return null;
}
// 判断头节点和value的关系
if (root.val == value) {
// 找到删除的节点后的操作
// 1. 如果该节点为叶子节点或者只有单个子树
if (root.left == null) {
return root.right;
}
if (root.right == null) {
return root.left;
}
// 2.如果该节点的左右子树都存在,找到右子树的最小节点,并将该最小节点放置在头结点处
TreeNode minNode = getMin(root.right);
// 删除右子树的最小节点,返回新的头节点
root.right = delete(root.right, minNode.val);
minNode.left = root.left;
minNode.right = root.right;
} else if (value < root.value) {
return delete(root.left, value);// 左子树
} else {
return delete(root.right, value);// 右子树
}
return root;
}
// 找到root为头节点的BST的最小节点
TreeNode getMin(TreeNode root) {
while (root.left != null) {
root = root.left;
}
return root;
}