# 平衡二叉树算法实现

```typedef struct BiTNode
{
int data;
int bf;
struct BiTNode *lchild, *rchild;
}BiTNode, *BiTree;
```

• 调整各个结点的BF值
• 旋转子树结构

```void R_Rotate(BiTree *T)
{
BiTree tmp;
tmp = (*T)->lchild;
(*T)->lchild = tmp->rchild;
tmp->rchild = (*T);
*T = tmp;
}

void L_Rotate(BiTree *T)
{
BiTree tmp;
tmp = (*T)->rchild;
(*T)->rchild = tmp->lchild;
tmp->lchild = (*T);
*T = tmp;
}
```

```//右平衡，右子树超重
void RightBalance(BiTree *T)
{
BiTree tmp, tmpr;
tmp = (*T)->rchild;
switch (tmp->bf)
{
case -1:
(*T)->bf = 0;
tmp->bf = 0;
L_Rotate(T);
break;
case 1:
tmpr = tmp->lchild;
switch (tmpr->bf)
{
case 1:
tmp->bf = -1;
(*T)->bf = 0;
break;
case -1:
tmp->bf = 0;
(*T)->bf = 1;
break;
case 0:
tmp->bf = (*T)->bf = 0;
}

tmpr->bf = 0;
//R_Rotate(&tmp);是错误的，因为不能修改上一级的指针
R_Rotate(&(*T)->rchild);
L_Rotate(T);
}
}```

```//左平衡，左子树超重
void LeftBlance(BiTree *T)
{
BiTree tmp,tmpr;
tmp = (*T)->lchild;
switch (tmp->bf)
{
case 1:
(*T)->bf = 0;
tmp->bf = 0;
R_Rotate(T);
break;
case -1:
tmpr = tmp->rchild;
switch (tmpr->bf)
{
case 1:
tmp->bf = 0;
(*T)->bf = -1;
break;
case -1:
tmp->bf = 1;
(*T)->bf = 0;
break;
case 0:
(*T)->bf = 0;
tmp->bf = 0;
break;
}//switch

tmpr->bf = 0;
//L_Rotate(&tmp);是错误的，因为不能修改上一级的指针
L_Rotate(&(*T)->lchild);
R_Rotate(T);
}
}
```

最后插入操作的主函数：

```bool InsertAVL(BiTree *T, int key, bool *taller)
{
if (*T ==NULL)
{
*T = (BiTree)malloc(sizeof(BiTNode));
(*T)->data = key;
(*T)->lchild = (*T)->rchild = NULL;
(*T)->bf = 0;
*taller = true;

return true;
}

if((*T)->data == key)
{
*taller = false;
return false;
}
else if((*T)->data > key)
{
if(!InsertAVL(&(*T)->lchild, key, taller))
return false;
if(*taller)
{
switch ((*T)->bf)
{
case 1:
LeftBlance(T);
*taller = false;
break;
case 0:
(*T)->bf = 1;
*taller = true;
break;
case -1:
(*T)->bf = 0;
*taller = false;
break;
}//switch
}//if
}//else if
else	//(*T)->data < key
{
if (!InsertAVL(&(*T)->rchild, key, taller))
return false;
if(*taller)
{
switch ((*T)->bf)
{
case 1:
(*T)->bf = 0;
*taller = false;
break;
case 0:
(*T)->bf = -1;
*taller = true;
break;
case -1:
RightBalance(T);
*taller = false;
}//switch
}//if
}//else

return true;
}
```

原文作者：stemon
原文地址: https://www.cnblogs.com/stemon/p/4839019.html
本文转自网络文章，转载此文章仅为分享知识，如有侵权，请联系博主进行删除。