平衡二叉树:
为了避免二叉排序树高度增长过快,降低二叉排序树的性能,所以有了平衡二叉树。规定任意结点的左右子树高度差绝对值不超过1,这样的二叉树称为平衡二叉树
实现代码:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
//平衡二叉树的结构体
typedef struct BBTree{
int data;
int advance;//平衡因子
BBTree *lchild;
BBTree *rchild;
}BBTree;
//左旋
void L(BBTree *&root){
BBTree *temp=root->rchild;//root指向结点A,temp指向结点
root->rchild=temp->lchild;//步骤1
temp->lchild=root;//步骤2
root->advance--;//更新结点A 的平衡因子
temp->advance--;//更新结点B 的平衡因子
root=temp;//步骤3
}
//右旋
void R(BBTree *&root){
BBTree *temp=root->lchild;//root指向结点A,temp指向结点B
root->lchild=temp->rchild;//步骤1
temp->rchild=root;//步骤2
root->advance--;
temp->advance--;
root=temp;//步骤3
}
//插入权值为v的结点
int insert(BBTree *&p,int key){
if(p==NULL){//到达空结点
p =(BBTree*)malloc(sizeof(BBTree));
p->data=key;
p->advance=0;
p->lchild=NULL;
p->rchild=NULL;
return 1;
}else{
if(key==p->data) {
printf("该数据已经存在");
return 0;
}else if(key <p->data){
insert(p->lchild,key);
p->advance++;//更新平衡因子
if(p->advance==2){
if(p->lchild->advance==1){
//LL型
printf("右单旋转\n");
R(p);
}else if(p->lchild->advance==-1){
//LR型
printf("先左后右双旋转\n");
L(p->lchild);
R(p);
}
}
return 1;
}else if(key>p->data){
//v比根结点的权值大
insert(p->rchild,key);//往右子树中插入
p->advance--;//更新平衡因子
if(p->advance==-2){
if(p->rchild->advance==-1){
//RR型
printf("左单旋转\n");
L(p);
}else if(p->rchild->advance==1){
//RL型
printf("先右后左双旋转\n");
R(p->lchild);
L(p);
}
}
return 1;
}
}
}
//建树
void createBBTree(BBTree *&p,int array[],int length){
for(int i=0;i<length;i++){
int a=insert(p,array[i]);
}
}
int main(){
int array[]={27,16,75,38,51};
BBTree *p=NULL;
createBBTree(p,array,5);
printf("%d ",p->rchild->data);
}
代码运行截图: