创立平衡二叉树,插入数据后旋转使其平衡,返回根结点
mooc-10
旋转操作原理参考
代码参考(有注释)
#include <stdio.h>
#include <stdlib.h>
typedef struct AVLNode *AVLTree;
struct AVLNode
{
int data;
AVLTree left;
AVLTree right;
int height;
};
int Max(int a,int b)
{
return a>b?a:b;
}
int getHeight(AVLTree a)
{
return a==NULL?-1:a->height;
}
AVLTree LLRotation(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 RRRotation(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->left),A->height)+1;
return B;
}
AVLTree LRRotation(AVLTree A)
{
A->left=RRRotation(A->left);
return LLRotation(A);
}
AVLTree RLRotation(AVLTree A)
{
A->right=LLRotation(A->right);
return RRRotation(A);
}
AVLTree insert(AVLTree T,int data)
{
if(!T)
{
T=(AVLTree)malloc(sizeof(struct AVLNode));
T->data=data;
T->left=NULL;
T->right=NULL;
T->height=0;
}
else
{
if(data<T->data)
{
T->left=insert(T->left,data);
if((getHeight(T->left)-getHeight(T->right))>1)
{
if(data<T->left->data) T=LLRotation(T);
else if(data>T->left->data) T=LRRotation(T);
}
}
else if(data>T->data)
{
T->right=insert(T->right,data);
if((getHeight(T->right)-getHeight(T->left))>1)
{
if(data<T->right->data) T=RLRotation(T);
else if(data>T->right->data) T=RRRotation(T);
}
}
}
T->height=Max(getHeight(T->left),getHeight(T->right))+1;
return T;
}
int main()
{
int n;
scanf("%d",&n);
AVLTree T=NULL;
for(int i=0;i<n;i++)
{
int num;
scanf("%d",&num);
T=insert(T,num);
}
printf("%d\n",T->data);
return 0;
}