您的位置:首页 > 理论基础 > 数据结构算法

数据结构——AVL平衡树

2015-01-04 00:09 190 查看
1、是二叉搜索树(Binary Search Tree)

2、树和所有左右子树高度之差为-1,0,1

平衡因子(balance factor)

  =右子树高度-左子树高度

平衡化旋转:

  1、从插入位置向根节点计算节点的平衡因子;

  2、若发现不平衡点(即平衡因子绝对值大于1),从此节点向下取两层;

  3、若三节点在同一直线上,则左单旋或右单旋,中间为旋转中心;

  4、否则左右双旋或右左双旋,最下为旋转中心。

AVLnode *AVLtree::insert(const string &item)
{
AVLnode *t=root,*newnode,*parent=NULL;
while(t!=NULL)
{
parent=t;
if(item==t->nodeValue)
return NULL;
else if(item<t->nodeValue)
t=t->left;
else
t=t->right;
}
newnode=creatAVLNode(item,NULL,NULL,parent);
if(parent==NULL)
root=newnode;
else if(item>parent->nodeValue)
parent->right=newnode;
else
parent->left=newnode;
treeSize++;

int bf=0,count=0;
AVLnode *cur=newnode,*p=newnode;
while(bf>=-1&&bf<=1&&cur!=root)
{
cur=cur->parent;
count++;
bf=balanceFactor(cur);
}

if(bf<-1||bf>1)
{
if(count==2) ;
else
{
for(int i=0;i<count-2;i++)
p=p->parent;
}
//all left
if(p->nodeValue<p->parent->nodeValue&&p->parent->nodeValue<cur->nodeValue)
rightRotate(p->parent);

//all right
else if(p->nodeValue>p->parent->nodeValue&&p->parent->nodeValue>cur->nodeValue)
leftRotate(p->parent);

//right left
else if(p->nodeValue<p->parent->nodeValue&&p->parent->nodeValue>cur->nodeValue)
rightleftRotate(p);
//left right
else if(p->nodeValue>p->parent->nodeValue&&p->parent->nodeValue<cur->nodeValue)
leftrightRotate(p);
}
return newnode;
}


View Code

平衡删除完整代码:

待补充
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: