🍊1. 二叉搜索树的概念
🍊2.二叉搜索树中的查找
public TreeNode searchBST(TreeNode root, int val) {
if(root==null) return null;
TreeNode curr=root;
while(curr!=null){
if(curr.val==val){
return curr;
}else if(curr.val<val){
curr=curr.right;
}else{
curr=curr.left;
}
}
//循环外面说明没有找到
return null;
}
🍊3.二叉搜索树的插入
NC372 插入二叉搜索树
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param root TreeNode类
* @param val int整型
* @return TreeNode类
*/
public TreeNode insertToBST (TreeNode root, int val) {
// write code here
if(root==null) return new TreeNode(val);
TreeNode curr=root;
TreeNode parent=null;
while(curr!=null){
if(curr.val==val){
break;
}else if(curr.val<val){
parent=curr;
curr=curr.right;
}else{
parent=curr;
curr=curr.left;
}
}
if(curr==parent.left){
parent.left=new TreeNode(val);
}else{
parent.right=new TreeNode(val);
}
return root;
}
}
🍊4.删除二叉搜索树中的一个节点(较复杂)
NC297 删除一个二叉搜索树中的节点
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param root TreeNode类
* @param key int整型
* @return TreeNode类
*/
public TreeNode deleteNode(TreeNode root, int key) {
root = delete(root,key);
return root;
}
private TreeNode delete(TreeNode root, int key) {
if (root == null) return null;
if (root.val > key) {
root.left = delete(root.left,key);
} else if (root.val < key) {
root.right = delete(root.right,key);
} else {
if (root.left == null) return root.right;
if (root.right == null) return root.left;
TreeNode tmp = root.right;
while (tmp.left != null) {
tmp = tmp.left;
}
root.val = tmp.val;
root.right = delete(root.right,tmp.val);
}
return root;
}
}
🍊5.判断是不是二叉搜索树(易错)
NC184 判断是不是二叉搜索树
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param root TreeNode类
* @return bool布尔型
*/
long pre = Long.MIN_VALUE;
public boolean isValidBST(TreeNode root) {
if (root == null) {
return true;
}
// 访问左子树
if (!isValidBST(root.left)) {
return false;
}
// 访问当前节点:如果当前节点小于等于中序遍历的前一个节点,说明不满足BST,返回 false;否则继续遍历。
if (root.val <= pre) {
return false;
}
pre = root.val;
// 访问右子树
return isValidBST(root.right);
}
}