a. AVL树有一个性质,F(h)=F(h-1)+F(h-2)+1
设斐波那契数列=h(x),则F(h)=h(h+2)-1,参考3.2节斐波那契部分可知,斐波那契数以指数形式增长,h(x)=hx/51/2
所以h=O(lgn)
b.c.d.
#include <stdio.h>
#include <stdlib.h>
typedef struct AVLNode
{
int key;
int hight;
AVLNode *p;
AVLNode *left;
AVLNode *right;
}AVL,*pAVL;
int max(int a,int b)
{
return a>=b?a:b;
}
int getHeight(pAVL x)
{
if(x==NULL)
return 0;
else
return x->hight;
}
void updateHight(pAVL x)
{
if(x)
{
x->hight=max(getHeight(x->left),getHeight(x->right))+1;
}
}
pAVL leftRotate(pAVL x)
{
if(x)
{
pAVL y=x->right;
if(!y)
return NULL;
if(x->p)
{
if(x==x->p->left)
x->p->left=y;
else
x->p->right=y;
}
y->p=x->p;
x->right=y->left;
y->left=x;
x->p=y;
updateHight(x);
updateHight(y);
return y;
}
return NULL;
}
pAVL rightRotate(pAVL y)
{
if(y)
{
pAVL x=y->left;
if(!x)
return NULL;
if(y->p)
{
if(y==y->p->left)
y->p->left=x;
else
y->p->right=x;
}
x->p=y->p;
y->left=x->right;
x->right=y;
y->p=x;
updateHight(y);
updateHight(x);
return x;
}
return NULL;
}
pAVL newNode(int key)
{
pAVL x=(pAVL)malloc(sizeof(AVL));
x->hight=1;
x->key=key;
x->left=NULL;
x->right=NULL;
x->p=NULL;
return x;
}
pAVL balance(pAVL x,int newKey)
{
if(getHeight(x->left)-getHeight(x->right)>=2)
{
if(newKey<=x->left->key)
{
return rightRotate(x);
}
else
{
leftRotate(x->left);
return rightRotate(x);
}
}
if(getHeight(x->right)-getHeight(x->left)>=2)
{
if(newKey>x->right->key)
{
return leftRotate(x);
}
else
{
rightRotate(x->right);
return leftRotate(x);
}
}
return x;
}
void AVLinsert(pAVL *root,int key)
{
pAVL z=newNode(key),x=*root,y=NULL;
//普通二叉搜索树插入
while(x)
{
y=x;
if(key<=x->key)
x=x->left;
else
x=x->right;
}
if(y==NULL)
{
(*root)=z;
return;
}
z->p=y;
if(key<=y->key)
{
y->left=z;
}
else
{
y->right=z;
}
//从插入节点开始向上更新高度
pAVL i=z->p;
while(i)
{
updateHight(i);
i=i->p;
}
//从插入节点的祖父开始向上检查平衡情况
i=z;
if(!i->p || !i->p->p)
return;
i=i->p->p;
while(i)
{
i=balance(i,key);
if(i->p==NULL)
(*root)=i;
i=i->p;
}
}
void preTrav(pAVL root,char c)
{
pAVL x=root;
if(!x)
return;
printf("key=%d,di=%c,height=%d ",x->key,c,x->hight);
preTrav(x->left,'L');
preTrav(x->right,'R');
}
void main()
{
pAVL root=NULL;
AVLinsert(&root,50);
AVLinsert(&root,40);
AVLinsert(&root,60);
AVLinsert(&root,55);
AVLinsert(&root,70);
AVLinsert(&root,53);
preTrav(root,'M');
getchar();
}