平衡二叉树本质上是一颗二叉查找树,只是在其基础上增加了“平衡”要求。所谓平衡是指,对AVL树的任意结点来说,其左子树与右子树的高度之差的绝对值不超过1,其中左子树与右子树的高度之差称为该结点的平衡因子。
定义结构体:
struct node{
int data,height; //v为结点权值,height为当前子树高度
node *lchild,*rchild; //左右孩子结点地址
};
新建结点:
node* newNode(int v){
node* Node=new node; //申请一个node型变量的地址空间
Node->data=v; //结点权值为v
Node->height=1; //结点高度初始为1
Node->lchild=Node->rchild=NULL; //初始状态下没有左右孩子
return Node; //返回新建结点的地址
}
获取当前结点高度:
//获取以root为根节点的子树的当前height
int getHeight(node* root){
if(root==NULL)
return 0;
return root->height;
}
平衡因子计算:
//平衡因子计算
int getBalanceFactor(node* root){
//左子树高度减右子树高度
return getHeight(root->lchild)-getHeight(root->rchild);
}
更新结点:
//更新结点root的Height
void updateHeight(node* root){
//max(左孩子的height,右孩子的height)+1
root->height=max(getHeight(root->lchild),getHeight(root->rchild))+1;
}
查找:
//search函数查找AVL树中数据域为x的结点
void search(node* root,int x){
if(root==NULL){ //空树,查找失败
printf("search failed\n");
return ;
}
if(x==root->data){ //查找成功,访问之
printf("%d\n",root->data);
}
else if(x<root->data){ //如果x比根结点的数据域小,说明x在左子树
search(root->lchild,x); //往左子树搜索x
}
else{ //如果x比根结点的数据域大,说明x在右子树
search(root->rchild,x); //往右子树搜索x
}
}
插入:
插入过程跟查找二叉树差不多,但要根据左旋和右旋调整平衡因子。
可按照下表进行调整:(BF为平衡因子)
树形 | 判定条件 | 调整方法 |
---|---|---|
LL | BF(root)= 2, BF(root->lchild)= 1 | 对root进行右旋 |
LR | BF(root)= 2, BF(root->lchild)= -1 | 先对root->lchild进行左旋,再对root进行右旋 |
RR | BF(root)= -2, BF(root->lchild)= -1 | 对root进行左旋 |
RL | BF(root)= -2, BF(root->lchild)= 1 | 先对root->lchild进行右旋,再对root进行左旋 |
具体方法可参考其他的博客,如下面这个链接
点击进入详细介绍
//左旋(left rotation)
void L(node* &root){
node* temp=root->rchild; //root指向结点A,temp指向结点B
root->rchild=temp->lchild; //步骤1
temp->lchild=root; //步骤2
updateHeight(root); //更新结点A的高度
updateHeight(temp); //更新结点B的高度
root=temp; //步骤3
}
//右旋(right rotation)
void R(node* &root){
node* temp=root->lchild; //root指向结点B,temp指向结点A
root->lchild=temp->rchild; //步骤1
temp->rchild=root; //步骤2
updateHeight(root); //更新结点A的高度
updateHeight(temp); //更新结点B的高度
root=temp; //步骤3
}
//插入结点
void insert(node* &root,int v){
if(root==NULL){ //到达空结点
root=newNode(v);
return ;
}
if(v<root->data){ //v比结点的权值小
insert(root->lchild,v); //往左子树插入
updateHeight(root); //更新树高
if(getBalanceFactor(root)==2){
if(getBalanceFactor(root->lchild)==1){ //LL型
R(root);
}
else if(getBalanceFactor(root->lchild)==-1){ //LR型
L(root->lchild);
R(root);
}
}
}
else{ //v比根结点的权值大
insert(root->rchild,v); //往右子树插入
updateHeight(root); //更新树高
if(getBalanceFactor(root)==-2){
if(getBalanceFactor(root->rchild)==-1){ //RR型
L(root);
}
else if(getBalanceFactor(root->rchild)==1){ //RL型
R(root->rchild);
L(root);
}
}
}
}
创建平衡二叉树:
//创建平衡二叉树
node* Create(int data[],int n){
node* root=NULL; //新建根结点root
for(int i=0;i<n;i++)
insert(root,data[i]); //将data[0]-data[n-1]插入二叉查找树中
return root; //返回根结点
}
删除:
未完待续