百度到这个的,肯定是个懒鬼
知道你懒,本博主宠宠你,特意敲出来了
#include <bits/stdc++.h>
using namespace std;
//左高、等高、右高
#define LH 1
#define EH 0
#define RH -1
enum Status { False, Success };
//定义树的数据类型
typedef int Type;
typedef struct Tree {
Type data;
int bf;
struct Tree *lchild, *rchild;
}Tree;
//左旋
Status R_Rotate(Tree **T)
{
Tree *p = (*T)->lchild;
(*T)->lchild = p->rchild;
p->rchild = *T;
*T = p;
return Success;
}
//右旋
Status L_Rotate(Tree **T)
{
Tree *p = (*T)->rchild;
(*T)->rchild = p->lchild;
p->lchild = *T;
*T = p;
return Success;
}
//左平衡:说明左边高了
Status LeftBalance(Tree **T)
{
Tree *p = (*T)->lchild;
switch (p->bf)
{
case LH:
{
(*T)->bf = p->bf = EH;
R_Rotate(T);
break;
}
case RH:
{
Tree *rp = p->rchild;
switch (rp->bf)
{
case LH:
{
(*T)->bf = RH;
p->bf = EH;
goto END;
}
case EH:
{
(*T)->bf = EH;
p->bf = EH;
goto END;
}
case RH:
{
(*T)->bf = EH;
p->bf = LH;
goto END;
}
END:
{
rp->bf = EH;
L_Rotate(&p);
R_Rotate(T);
}
}
}
}
return Success;
}
//右平衡:说明右边高了
Status RightBalance(Tree **T)
{
Tree *p = (*T)->rchild;
switch (p->bf)
{
case RH:
{
(*T)->bf = p->bf = EH;
L_Rotate(T);
break;
}
case LH:
{
Tree *lp = p->lchild;
switch (lp->bf)
{
case LH:
{
(*T)->bf = EH;
p->bf = RH;
goto END;
}
case EH:
{
(*T)->bf = EH;
p->bf = EH;
goto END;
}
case RH:
{
(*T)->bf = LH;
p->bf = EH;
goto END;
}
END:
{
lp->bf = EH;
R_Rotate(&p);
L_Rotate(T);
}
}
}
}
return Success;
}
Status InsertAVL(Tree **T, Type key, bool &taller)
{
//没找到
if (!(*T))
{
*T = (Tree *)malloc(sizeof(Tree));
(*T)->lchild = (*T)->rchild = NULL;
(*T)->data = key;
(*T)->bf = EH;
taller = true;
}
else
{
if (key == (*T)->data)
{
taller = false;
return False;
}
if ((*T)->data > key)
{
if (!InsertAVL(&((*T)->lchild), key, taller))
return False;
if (taller)
{
switch ((*T)->bf)
{
case LH:
{
LeftBalance(T);
taller = false;
break;
}
case EH:
{
(*T)->bf = LH;
taller = false;
break;
}
case RH:
{
(*T)->bf = EH;
taller = false;
break;
}
}
}
}
else
{
if (!InsertAVL(&((*T)->rchild), key, taller))
return False;
if (taller)
{
switch ((*T)->bf)
{
case LH:
{
(*T)->bf = EH;
taller = false;
break;
}
case EH:
{
(*T)->bf = RH;
taller = false;
break;
}
case RH:
{
LeftBalance(T);
taller = false;
break;
}
}
}
}
}
return Success;
}
//先序遍历
void Ergodic(Tree *T)
{
if (T)
{
Ergodic(T->lchild);
cout << T->data<<" ";
Ergodic(T->rchild);
}
}
int main()
{
int a[] = { 3,2,1,4,5,6,7,10,9,8 };
Tree *T = NULL;
bool taller = false;
for (auto i : a)
{
InsertAVL(&T, i, taller);
}
Ergodic(T);
return 0;
}