概念分析
- 平衡二叉树也叫平衡二叉搜索树,又被称为AVL树,它能保证查询效率较高
- 他具有以下特点:它是一颗空树或者它的左右两颗子树的高度差的绝对值不大于一,并且左右子树都是平衡二叉树,其也满足二叉排序树的特点
小练习
看过上述的概念之后,我们应该可以分辨哪些是平衡二叉树。
为什么出现平衡二叉树
上一章讲的是二叉排序树,其效率一般是大于链表的,那么如果我们添加的数列是{1,2,3,4,5,6}呢?
我们会发现一个问题,我们构建的BST成为了一个链表形状,但是效率却不如链表,因为进行遍历查找还需要判断是否有左子结点。
建立节点类和AVL类
结点类
class Node{
int value;
Node left;
Node right;
public Node(int value){
this.value = value;
}
/**
* 查找待删除的节点
* @param value 待删除节点的值
* @return 返回被删除的节点 不存在该节点则返回null
*/
public Node search(int value){
if(this.value == value){
return this;
} else if (value < this.value){
// 二叉排序树的左子结点都小于其父结点的值
if (this.left == null){
return null;
}else {
return this.left.search(value);
}
}else {
// 如果不小于其父结点的值 那么可以判断在右子结点
if (this.right == null){
return null;
}else {
return this.right.search(value);
}
}
}
/**
* 查找待删除节点的父结点
* @param value 待删除节点的值
* @return 待删除节点的父结点
*/
public Node searchParent(int value){
if((this.left != null && this.left.value == value) || (this.right != null && this.right.value == value)){
return this;
} else {
if (value < this.value && this.left != null){
return this.left.searchParent(value);
} else if (value >= this.value && this.right != null){
return this.right.searchParent(value);
}else {
return null;
}
}
}
/**
* BST添加节点
* @param node 待添加的节点
*/
public void add(Node node){
if(node == null){
return;
}
// 添加的节点小于此节点的值 我们将其添加到左子结点处
if (node.value < this.value){
if (this.left == null){
this.left = node;
}else {
// 如果其左子结点不为空,那么我们将要插入的节点与其左子结点进行比较
this.left.add(node);
}
}else {
// 相等的或者大于的都添加到右子结点
if (this.right == null){
this.right = node;
}else {
this.right.add(node);
}
}
// 左旋转发生在添加之后,如果右子树高度比左子树的高度超过一
if (this.rightHeight() - 1 > this.leftHeight()