内容:
- 平衡二叉树简介
- 结点的构造并新建
- 获得高度
- 计算平衡因子并更新
- AVL查找操作
- 左旋与右旋
- AVL插入操作
- AVL树的建立
1、 平衡二叉树简介
使树的高度在每次插入元素后,任然保持O(logn)的级别;
AVL树仍然是一棵二叉查找树;
对AVL树的任意结点来说,其左子树与右子树高度之差的绝对值不超过1,其中左子树与右子树的高度之差称为该节点的平衡因子;
2、结点的构造
struct node{
int v,height;//v为结点权值,height为当前子树的高度
node *lchild,*rchild;//左右孩子结点地址
}
新建结点
node* newNode(int v){
node* Node=new node;
Node->v=v;
Node->height=1;
Node->lchild=Node->rchild=NULL;
return Node;
}
3、获得高度
int getHeight(node* root){
if(root==NULL)
return 0;//如果为空,高度返回0
return root->height;//返回当前结点高度
}
4、计算平衡因子
int BalanceFactor(node* root){
return getHeight(root->lchild)-getHeight(root->rchild);
更新高度
void updateHeight(node* root){
root->height=max(getHeight(root->lchild),getHeight(root->rchild))+1;
}
5、AVL查找操作
void search(node* root,int x){
if(root==NULL)
return;
if(x==root->v)
cout<<root->v;
else if(x<root->v)
search(root->lchild,x);
else
search(root->rchild,x);
}
6、左旋与右旋(自行百度)
//左旋
void L(node* root){
node* temp=root->rchild;
root->rchild=temp->lchild;
temp->lchild=root;
updateHeight(root);
updateHeight(temp);
root=temp;
}
7、AVL插入操作
void insertAVL(node* &root,int v){
if(root==NULL){
root=newNode(v);
return;
}
if(v<root->v){
insertAVL(root->lchild,v);//将v值插入左子树中
updateHeight(root);//更新树高度
if(getBalanceFactor(root)==2){
if(getBalanceFactor(root->lchild)==1){//LL型
R(root);
}else if(getBalanceFactor(root->lchild)==-1){
L(root->lchild);
R(root);
}
}
}else{
insertAVL(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);
}
}
}
}
8、AVL树的建立
node* createAVL(int data[],int n){
node* root=NULL;
for(int i=0;i<n;i++)
insertAVL(root,data[i]);//将data[0]~data[n-1]插入AVL树中
return root;
}
由于学习任务重,这篇博文仅仅是个人代码的存录,并没有做解析,等以后有时间会更新这篇文章的,望海涵。。。拜拜