1、搜索二叉树插入
public static Node createSearchTree(Node root, int val) {
if (root == null) {
return new Node(val);
}
while (root != null) {
if (root.val == val) {
break;
}
if (root.val > val) {
if (root.right == null) {
root.right = new Node(val);
} else {
root = root.right;
}
} else {
if (root.left == null) {
root.left = new Node(val);
} else {
root = root.left;
}
}
}
return root;
}
public static Node insertIntoBST(Node root,int val){
if (root == null){
return new Node(val);
}
if (root.val < val){
root.right = insertIntoBST(root.right, val);
}else {
root.left = insertIntoBST(root.left, val);
}
return root;
}
2、二叉搜索树的查找
/**
* 5
* 3 7
* 1 4 6 8
*
*/
private static boolean search(Node node,int data){
if(node==null){
return false;
}
while(node!=null){
if(node.data==data){
return true;
}else if(data>node.data){
node=node.right;
}else{
node=node.left;
}
}
return false;
}
3、创建搜索二叉树
private static Node create(int[] arr,int index){
if (index>=arr.length||index<0) {
return null;
}
Node root = new Node();
root.data=arr[index];
root.left = create(arr, 2*index+1);
root.right = create(arr, 2*index+2);
return root;
}
4、判断是否为搜索二叉树
- 中序遍历判断是否有序
- 分治:left<root<right
public static boolean isValidBST(Node root){
if (root == null){
return true;
}
boolean left = isValidBST(root.left);
boolean right = isValidBST(root.right);
boolean res = left && right;
if (root.left != null && root.left.val >= root.val){
res = false;
}
if (root.right != null && root.right.val <= root.val){
res = false;
}
return res;
}
简化:
isSearchBinary(root, Integer.MIN_VALUE, Integer.MAX_VALUE);
public static boolean isSearchBinary(Node root, int min, int max){
if (root == null){
return true;
}
if (root.val <= min || root.val >= max){
return false;
}
return isSearchBinary(root.left, min, root.val)&&
isSearchBinary(root.right, root.val, max);
}
5、删除节点
删除节点分为三种情况:
- 只有左节点 替换为右
- 只有右节点 替换为左
- 有左右子节点 左子节点连接到右边最左节点即可或右节点连接到左子节点的最右节点
public static Node deleteNodeBST(Node root, int val) {
if (root == null) {
return null;
}
if (root.val > val) {
root.left = deleteNodeBST(root.left, val);
} else if (root.val < val) {
root.right = deleteNodeBST(root.right, val);
} else {
if (root.left == null) {
return root.right;
} else if (root.right == null) {
return root.left;
} else {
// 两个都不为空
Node cur = root.right;
while (cur.left != null) {
cur = cur.left;
}
cur.left = root.left;
return root.right;
}
}
return root;
}