二叉搜索树介绍
二叉搜索树又称二叉排序树,它或者是一棵空树,或者是具有以下性质的二叉树:
1.若它的左子树不为空,则左子树上所有节点的值都小于根节点的值
2.若它的右子树不为空,则右子树上所有节点的值都大于根节点的值
3.它的左右子树也分别为二叉搜索树
int a [] = {5,3,4,1,7,8,2,6,0,9};
查找
实现如下
public boolean search(int key) {
if(root == null) {
return false;
}
Node cur = root;
while (cur != null) {
if(cur.val == key) {
return true;
}else if(cur.val < key){
cur = cur.right;
}else {
cur = cur.left;
}
}
return false;
}
插入
- 如果树为空树,即根 == null,直接插入
- 如果树不是空树,按照查找逻辑确定插入位置,插入新结点
实现如下
public void insert(int key) {
Node now = new Node(key);
if(root == null){
root = now;
return;
}
Node p = null;
Node cur = root;
while(cur != null){
if(cur.val == key) {
return;
}else if(cur.val < key){
p = cur;
cur = cur.right;
}else {
p = cur;
cur = cur.left;
}
}
if(p.val < key){
p.right = now;
}else{
p.left = now;
}
}
删除
设待删除结点为 cur, 待删除结点的双亲结点为 parent
- cur.left == null
cur 是 root,则 root = cur.right
cur 不是 root,cur 是 parent.left,则 parent.left = cur.right
cur 不是 root,cur 是 parent.right,则 parent.right = cur.right - cur.right == null
cur 是 root,则 root = cur.left
cur 不是 root,cur 是 parent.left,则 parent.left = cur.left
cur 不是 root,cur 是 parent.right,则 parent.right = cur.left - cur.left != null && cur.right != null
需要使用替换法进行删除,即在它的右子树中寻找中序下的第一个结点(关键码最小),用它的值填补到被删除节点中,再来处理该结点的删除问题
实现如下
public void removeNode(Node p ,Node cur){
if(cur.left == null){
if(cur == root){
root = cur.right;
}else if(cur == p.left){
p.left = cur.right;
}else{
p.right = cur.right;
}
}else if(cur.right == null){
if(cur == root){
root = cur.left;
}else if(cur == p.left){
p.left = cur.left;
}else{
p.right = cur.left;
}
}else{
Node tp = cur;
Node t = cur.right;
while(t.left != null){
tp = t;
t = t.left;
}
cur.val = t.val;
if(tp.right == t){
tp.left = t.right;
}else{
tp.right = t.right;
}
}
}
public void remove(int key){
Node p = null;
Node cur = root;
while(cur!=null){
if(cur.val == key){
removeNode(p,cur);
return ;
}else if(cur.val > key){
p = cur ;
cur = cur.left;
}else{
p = cur ;
cur = cur.right;
}
}
}