Now given a sequence of insertions, you are supposed to tell the root of the resulting AVL tree.
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.
#include<iostream>
using namespace std;
typedef struct AVLTreeNode* AVLTree;
struct AVLTreeNode {
int v;
AVLTree left, right;
int height;
};
int GetHeight(AVLTree T);
AVLTree Insert(AVLTree T, int V);
int main()
{
int i, N, V;
AVLTree T = NULL;
cin >> N;
for (i = 0; i < N; i++) {
cin >> V;
T = Insert(T, V);
}
cout << T->v << endl;;
return 0;
}
int Max(int a, int b)
{
return a > b ? a : b;
}
AVLTree SingleRightRotation(AVLTree A)
{
AVLTree B;
B = A->right;
A->right = B->left;
B->left = A;
A->height = Max(GetHeight(A->left), GetHeight(A->right)) + 1; //左右子树最大高度+1
B->height = Max(GetHeight(B->right), A->height) + 1; //同上
return B;
}
AVLTree SingleLeftRotation(AVLTree A)
{
AVLTree B;
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 DoubleLeftRightRotation(AVLTree A)
{
A->left = SingleRightRotation(A->left);
return SingleLeftRotation(A);
}
//右左双旋:先对右子树左单旋,再对树右单旋
AVLTree DoubleRightLeftRotation(AVLTree A)
{
A->right = SingleLeftRotation(A->right);
return SingleRightRotation(A);
}
AVLTree Insert(AVLTree T, int V)
{
if (!T) {
T = (AVLTree)malloc(sizeof(struct AVLTreeNode));
T->height = 0;
T->left = T->right = NULL;
T->v = V;
}
else if (V < T->v) {
T->left = Insert(T->left, V); //值小于T的值插入左子树
if (GetHeight(T->left) - GetHeight(T->right) == 2) { //若左右两树不平衡
if (V < T->left->v) //麻烦节点在左子树左边LL旋转
T = SingleLeftRotation(T);
else T = DoubleLeftRightRotation(T); //麻烦节点在左子树右边LR旋转
}
}
else if (V > T->v) {
T->right = Insert(T->right, V); //值大于T->v插入右子树
if (GetHeight(T->left) - GetHeight(T->right) == -2) {
if (V > T->right->v) //麻烦节点在右子树右边RR旋转
T = SingleRightRotation(T);
else T = DoubleRightLeftRotation(T); //麻烦节点在右子树左边RL旋转
}
}
T->height = Max(GetHeight(T->left), GetHeight(T->right)) + 1; //总树高
return T;
}
int GetHeight(AVLTree T)
{
int MaxH, HL, HR;
if (T) {
HL = GetHeight(T->left); //递归得到左子树高度
HR = GetHeight(T->right); //同上,右子树
MaxH = HL > HR ? HL : HR; //最大高度
return (MaxH + 1); //返回最大高度+1
}
else return 0;
}