![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/4cab4bd09ab9967b92bacef380020c43.png)
typedef struct AVLNode *Position;
typedef Position AVLTree;
struct AVLNode {
ElementType Data;
AVLTree Left;
AVLTree Right;
int Height;
};
int Max(int a, int b)
{
return a > b ? a : b;
}
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/bf1a21d631d7a1638fb85bcf4c463326.png)
AVLTree SingleRightRotation(AVLTree A)
{
AVLTree B = A->Right;
A->Right = B->Left;
B->Left = A;
A->Height = Max(GetHeight(A->Left), GetHeight(A->Right)) + 1;
B->Height = Max(GetHeight(B->Right), A->Height) + 1;
}
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/7059cb8ff3b9a87940f3672417b3f5da.png)
AVLTree SingleLeftRotation(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;
}
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/582b0b89168993844f99ea7cb4ae4d06.png)
AVLTree DoubleLeftRightRotation(AVLTree A)
{
A->Left = SingleRightRotation(A->Left);
return SingleLeftRotation(A);
}
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/e969d2a65ef82d9c1cb0a93eeddff740.png)
AVLTree DoubleRightLeftRotation(AVLTree A)
{
A->Right = SingleLeftRotation(A->Right);
return SingleRightRotation(A);
}
AVLTree Insert(AVLTree T, ElementType X)
{
if (!T) {
T = (AVLTree)malloc(sizeof(struct AVLNode));
T->Data = X;
T->Height = 0;
T->Left = T->Right = NULL;
}
else if (X < T->Data) {
T->Left = Insert(T->Left, X);
if (GetHeight(T->Left) - GetHeight(T->Right) == 2) {
if (X < T->Left->Data)
T = SingleLeftRotation(T);
else
T = DoubleLeftRightRotation(T);
}
}
else if (X > T->Data) {
T->Right = Insert(T->Right, X);
if (GetHeight(T->Left) - GetHeight(T->Right) == -2) {
if (X > T->Right->Data)
T = SingleRightRotation(T);
else
T = DoubleRightLeftRotation(T);
}
}
T->Height = Max(GetHeight(T->Left), GetHeight(T->Right)) + 1;
return T;
}