MARK一篇关于AVL树的博客文章:数据结构图文解析之:AVL树详解及C++模板实现
一、AVL结构定义
struct AVLNode
{
struct AVLNode *lchild,*rchild;
int key;
int height;//保存树的高度
};
二、几个函数
int Max(int a,int b)
{
return a>b?a:b;
}
int ComputeHeight(struct AVLNode *T)
{
if(T)
return T->height;
return 0;
}
三、AVL的旋转
struct AVLNode *leftRotation(struct AVLNode *root)//左旋操作,对应于RR
{
struct AVLNode *p=root->rchild;
root->rchild=p->lchild;
p->lchild=root;
root->height=Max(ComputeHeight(root->lchild),ComputeHeight(root->rchild))+1;
p->height=Max(ComputeHeight(p->lchild),ComputeHeight(p->rchild))+1;
return p;
}
struct AVLNode *rightRotation(struct AVLNode *root)//右旋操作,对应于LL
{
struct AVLNode *p=root->lchild;
root->lchild=p->rchild;
p->rchild=root;
root->height=Max(ComputeHeight(root->lchild),ComputeHeight(root->rchild))+1;
p->height=Max(ComputeHeight(p->lchild),ComputeHeight(p->rchild))+1;
return p;
}
struct AVLNode *rightleftRotation(struct AVLNode *root)//先右旋,再左旋操作,对应于RL
{
root->rchild=rightRotation(root->rchild);//失衡节点右儿子进行一次右旋操作
return leftRotation(root);//失衡节点进行一次左旋
}
struct AVLNode *leftrightRotation(struct AVLNode *root)//先左旋,再右旋操作,对应于LR
{
root->lchild=leftRotation(root->lchild);//失衡节点左儿子进行一次左旋操作
return rightRotation(root);//失衡节点进行一次右旋
}
四、AVL的插入
void InsertNode(int e,struct AVLNode **T)
{
if((*T)==NULL)
{
(*T)=(struct AVLNode*)malloc(sizeof(struct AVLNode));
(*T)->lchild=(*T)->rchild=NULL;
(*T)->key=e;
(*T)->height=0;
}
else if(e<((*T)->key))
{
InsertNode(e,&(*T)->lchild);//插入左子树
if(ComputeHeight((*T)->lchild)-ComputeHeight((*T)->rchild)==2)//失衡
{
e<(*T)->lchild->key?((*T)=rightRotation(*T)):((*T)=leftrightRotation(*T));
}
}
else if(e>(*T)->key)
{
InsertNode(e,&(*T)->rchild);//插入右子树
if(ComputeHeight((*T)->rchild)-ComputeHeight((*T)->lchild)==2)
{
e>(*T)->rchild->key?((*T)=leftRotation(*T)):((*T)=rightleftRotation(*T));
}
}
(*T)->height=Max(ComputeHeight((*T)->lchild),ComputeHeight((*T)->rchild))+1;//更新节点高度
}