int Max(int a, int b){
if(a>b)
return a;
else
return b;
}
int GetHeight(AVLTree A){
if(A==NULL)
return 0;
return A->Height;
}
AVLTree LeftRotate(AVLTree A){
AVLTree B=A->Right;
A->Right=B->Left;
B->Left=A; //这里需要不断的去刷新height
A->Height = Max(GetHeight(A->Left), GetHeight(A->Right)) + 1;//刷新一下子树的高度。
B->Height = Max(GetHeight(B->Right), A->Height) + 1;//此函数是输一个老根的树,返回一个带有新根的树;这里算新根的高度
return B;
}//左旋,适用于右右模式,可用于右左模式,左右模式
AVLTree RightRotate(AVLTree A){
AVLTree B=A->Left;
A->Left=B->Right;
B->Right=A;
A->Height=Max(GetHeight(A->Left), GetHeight(A->Right))+1;//刷新子树的高度
B->Height=Max(GetHeight(B->Left),A->Height)+1;//得到新的生成树高度
return B;
}//右旋,适用于左左模式,可用于右左模式,左右模式
AVLTree RightLeftRotate(AVLTree A){
A->Right = RightRotate(A->Right);
return LeftRotate(A);
}
AVLTree LeftRightRotate(AVLTree A){
A->Left = LeftRotate(A->Left);
return RightRotate(A);
}
AVLTree Insert(AVLTree T,int X){
if(!T){
T=(AVLTree)malloc(sizeof(struct AVLNode));
T->Key=X;
T->Height=1;
T->Left=T->Right=NULL;
}
else if(X<T->Key){ //插入左子树
T->Left=Insert(T->Left,X);
if(GetHeight(T->Left)-GetHeight(T->Right)>=2){
if(X<T->Left->Key)//这一步看是左左模式还是左右模式
T=RightRotate(T);
else
T=LeftRightRotate(T);
}
}
else if(X>T->Key){
T->Right=Insert(T->Right, X);
if(GetHeight(T->Right)-GetHeight(T->Left)>=2){
if (X>T->Right->Key)//这一步就是看是右右模式还是右左模式
T=LeftRotate(T);
else
T=RightLeftRotate(T);
}
}
T->Height=Max(GetHeight(T->Left), GetHeight(T->Right))+1;
return T;
}
平衡二叉树的插入
最新推荐文章于 2024-09-26 10:12:09 发布