概念
二叉搜索树又称二叉排序树,它或者是一棵空树**,或者是具有以下性质的二叉树:
若它的左子树不为空,则左子树上所有节点的值都小于根节点的值
若它的右子树不为空,则右子树上所有节点的值都大于根节点的值
它的左右子树也分别为二叉搜索树
操作
搜索树的操作有搜索,插入,删除,其中删除操作最为复杂:
public class TestBinarySearchTree {
static class TreeNode {
public int val;
public TreeNode left;
public TreeNode right;
public TreeNode(int val) {
this.val = val;
}
}
public TreeNode root ;
public boolean search(int val) {
if(root == null) {
return false;
}
TreeNode cur = root;
while (cur != null) {
if(cur.val == val) {
return true;
}else if(cur.val > val) {
cur = cur.left;
}else {
cur = cur.right;
}
}
return false;
}
public boolean insert(int val) {
if(root == null) {
root = new TreeNode(val);
return true;
}
TreeNode cur = root;
TreeNode parent = null;
while (cur != null) {
if(cur.val < val) {
parent = cur;
cur = cur.right;
}else if(cur.val > val) {
parent = cur;
cur = cur.left;
}else {
return false;//不能插入相同的数字
}
}
if(parent.val < val) {
parent.right = new TreeNode(val);;
}else {
parent.left = new TreeNode(val);;
}
return true;
}
public boolean remove(int key) {
if(root == null) {
return false;
}
TreeNode cur = root;
TreeNode parent = null;
while (cur != null) {
if(cur.val < key) {
parent = cur;
cur = cur.right;
}else if (cur.val > key) {
parent = cur;
cur = cur.left;
}else {
removeNode(parent,cur);
return true;
}
}
return false;
}
public void removeNode(TreeNode parent,TreeNode cur) {
if(cur.left == null) {
if(cur == root) {
root = cur.right;
}else if(parent.right == cur) {
parent.right = cur.right;
}else {
parent.left = cur.right;
}
}else if(cur.right == null) {
if(cur == root) {
root = cur.left;
}else if(parent.left == cur) {
parent.left = cur.left;
}else {
parent.right = cur.left;
}
}else {
TreeNode target = cur.right;
TreeNode targetParent = cur;
while (target.left != null) {
targetParent = target;
target = target.left;
}
cur.val = target.val;
if(target == targetParent.left) {
targetParent.left = target.right;
}else {
targetParent.right = target.right;
}
}
}
}