标注: AVL树的基本题,仔细想想动手画画RS, LS,LRS,RLS!!code
04-树5 Root of AVL Tree (25分)
An AVL tree is a self-balancing binary search tree. In an AVL tree, the heights of the two child subtrees of any node differ by at most one; if at any time they differ by more than one, rebalancing is done to restore this property. Figures 1-4 illustrate the rotation rules.
Input Specification:
Each input file contains one test case. For each case, the first line contains a positive integer N (≤20) which is the total number of keys to be inserted. Then N distinct integer keys are given in the next line. All the numbers in a line are separated by a space.
Output Specification:
For each test case, print the root of the resulting AVL tree in one line.
Sample Input 1:
5
88 70 61 96 120
Sample Output 1:
70
Sample Input 2:
7
88 70 61 96 120 90 65
Sample Output 2:
#include
#include
#include
#define MAX(a,b) (a>b)?a:b
typedef int Element;
typedef struct AVLtreeNode* AVLTree;
struct AVLtreeNode
{
Element data;
AVLTree left;
AVLTree right;
int height;
};
AVLTree AVl_Insertion(Element x,AVLTree T);
Element GetHeight(AVLTree A);
AVLTree SingleLeftRotation(AVLTree A);
AVLTree SingleRightRotation(AVLTree A);
AVLTree DoubleLeftRightRotation(AVLTree A);
AVLTree DoubleRightLeftRotation(AVLTree A);
int main()
{
// freopen("11.txt","r",stdin);
int N;
AVLTree T = NULL;
scanf("%d",&N);
while (N--)
{
int x;
scanf("%d",&x);
T = AVl_Insertion(x,T);
}
printf("%d\n",T->data);
return 0;
}
Element GetHeight(AVLTree A)
{
int HL,HR,Maxh;
if (A)
{
HL = GetHeight(A->left);
HR = GetHeight(A->right);
Maxh = MAX(HL,HR);
return (Maxh+1);
}
else return 0;
}
AVLTree AVl_Insertion(Element x,AVLTree T)
{
if(!T)
{
T = (AVLTree)malloc(sizeof(struct AVLtreeNode));
T->data=x;
T->height = 0;
T->left=T->right=NULL;
}
else if (x < T->data)
{
T->left = AVl_Insertion(x,T->left);
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 = AVl_Insertion(x,T->right);
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;
}
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),GetHeight(B->right)) + 1;
return B;
}
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->left),GetHeight(B->right)) + 1;
return B;
}
AVLTree DoubleLeftRightRotation(AVLTree A)
{
A->left = SingleRightRotation(A->left);
return SingleLeftRotation(A);
}
AVLTree DoubleRightLeftRotation(AVLTree A)
{
A->right = SingleLeftRotation(A->right);
return SingleRightRotation(A);
}