概念
二叉搜索树又称二叉排序树,它或者是一棵空树,或者是具有以下性质的二叉树:
若它的左子树不为空,则左子树上所有节点的值都小于根节点的值
若它的右子树不为空,则右子树上所有节点的值都大于根节点的值
它的左右子树也分别为二叉搜索树
操作
操作—查找
操作—插入
- 如果树为空树,即根 == null,直接插入
- 如果树不是空树,按照查找逻辑确定插入位置,插入新结点
操作—删除
设待删除结点为 cur, 待删除结点的双亲结点为 parent
-
cur 是 root,则 root = cur.right -
cur 不是 root,cur 是 parent.left,则 parent.left = cur.right -
cur 不是 root,cur 是 parent.right,则 parent.right = cur.right
-
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
- 需要使用替换法进行删除,即在它的右子树中寻找中序下的第一个结点(关键码最小),用它的值填补到被删除节比特科技点中,再来处理该结点的删除问题
代码实现
class Node {
public int val;
public Node left;
public Node right;
public Node(int val) {
this.val = val;
}
@Override
public String toString() {
return "bstree.Node{" +
"val=" + val +
'}';
}
}
public class BSTree {
public Node root;
public BSTree() {
root = null;
}
public boolean find(int key) {
Node cur = root;
while (cur != null) {
if (cur.val == key) {
return true;
} else if (cur.val > key) {
cur = cur.left;
} else {
cur = cur.right;
}
}
return false;
}
public void insert(int key) {
if (root == null) {
root = new Node(key);
return;
}
Node cur = root;
Node parent = null;
while (cur != null) {
if (cur.val == key) {
throw new RuntimeException("BSTree中不允许重复的key出现");
} else if (cur.val > key) {
parent = cur;
cur = cur.left;
} else {
parent = cur;
cur = cur.right;
}
}
Node node = new Node(key);
if (key > parent.val) {
parent.right = node;
} else {
parent.left = node;
}
}
public boolean remove(int key) {
Node parent = null;
Node cur = root;
while (cur != null) {
if (cur.val == key) {
removeKey(parent, cur);
return true;
} else if (cur.val > key) {
parent = cur;
cur = cur.left;
} else {
parent = cur;
cur = cur.right;
}
}
return false;
}
private void removeKey(Node parent, Node cur) {
if (cur.left == null) {
if (cur == root) {
root = cur.right;
} else if (cur == parent.right) {
parent.right = cur.right;
} else {
parent.left = cur.right;
}
}
else if (cur.right == null) {
if (cur == root) {
root = cur.left;
} else if (cur == parent.right) {
parent.right = cur.left;
} else {
parent.left = cur.left;
}
}
else {
Node goat = cur.right;
Node goatParent = cur;
while (goat.left != null) {
goatParent = goat;
goat = goatParent.left;
}
cur.val = goat.val;
if (goatParent == cur) {
goatParent.right = goat.right;
} else {
goatParent.left = goat.right;
}
}
}
}
性能分析
插入和删除操作都必须先查找,查找效率代表了二叉搜索树中各个操作的性能。
对有n个结点的二叉搜索树,若每个元素查找的概率相等,则二叉搜索树平均查找长度是结点在二叉搜索树的深度的函数,即结点越深,则比较次数越多。
但对于同一个关键码集合,如果各关键码插入的次序不同,可能得到不同结构的二叉搜索树: 最优情况下,二叉搜索树为完全二叉树,其平均比较次数为:
l
o
g
2
N
log_2 N
log2?N 最差情况下,二叉搜索树退化为单支树,其平均比较次数为:
N
2
\frac{N}{2}
2N?
|