Root of AVL Tree
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.
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.
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:
88
#include <stdio.h>
#include <malloc.h>
#define null 0
typedef struct TreeNode* AVLTree;
struct TreeNode{
int elem;
AVLTree left;
AVLTree right;
int height;
};
int max(int a,int b){
return a>b?a:b;
}
int getHeight(AVLTree T){
if(T==null) return -1;
else return T->height;
}
AVLTree singleLeftRotation(AVLTree T){
//左单旋:破坏点在左子树的左子树上
AVLTree B = T->left;
T->left = B->right;
B->right = T;
//更新T,B的树高
T->height = max(getHeight(T->left),getHeight(T->right))+1;
B->height = max(getHeight(B->left),getHeight(B->right))+1;
return B;
}
AVLTree singleRightRotation(AVLTree T){
//右单旋:破坏点在右子树的右子树上
AVLTree B = T->right;
T->right = B->left;
B->left = T;
//更新T,B的树高
T->height = max(getHeight(T->left),getHeight(T->right))+1;
B->height = max(getHeight(B->left),getHeight(B->right))+1;
return B;
}
AVLTree doubleLeftRightRotation(AVLTree T){
//左右双旋:破坏点在左子树的右子树上
T->left = singleRightRotation(T->left);
return singleLeftRotation(T);
}
AVLTree doubleRightLeftRotation(AVLTree T){
//右左双旋:破坏点在右子树的左子树上
T->right = singleLeftRotation(T->right);
return singleRightRotation(T);
}
AVLTree AVLInsert(AVLTree T,int n){
//插入过程一定会访问被插结点的所有祖宗结点,更新所有祖宗的树高
//在AVL上插入一个数,并返回树根
if(T==null){
T = (AVLTree)malloc(sizeof(struct TreeNode));
T->elem = n;
T->left = T->right = null;
T->height = 0;
}
else{
if(n>T->elem){
T->right = AVLInsert(T->right,n);
if(getHeight(T->right)-getHeight(T->left)==2){
if(n<T->right->elem){
//破坏点在右子树的左子树上
T = doubleRightLeftRotation(T);
}
else//破坏点在右子树的右子树上
T = singleRightRotation(T);
}
}
if(n<T->elem){
T->left = AVLInsert(T->left,n);
if(getHeight(T->left)-getHeight(T->right)==2){
if(n>T->left->elem){
//破坏点在左子树的右子树上
T = doubleLeftRightRotation(T);
}
else//破坏点在左子树的左子树上
T = singleLeftRotation(T);
}
}
}
T->height = max(getHeight(T->left),getHeight(T->right))+1;
return T;
}
AVLTree makeAVL(int N){
AVLTree T = null;
int e;
while(N--){
scanf("%d",&e);
T = AVLInsert(T,e);
}
return T;
}
void freeTree(AVLTree T){
if(T->left) freeTree(T->left);
if(T->right) freeTree(T->right);
free(T);
}
int main(){
int N;
if(scanf("%d\n",&N)){
AVLTree T = makeAVL(N);
printf("%d",T->elem);
freeTree(T);
}
return 0;
}