AVL Tree
#include<stdio.h>
struct avl{
int num;
struct avl *left, *right;
int height;
};
int max(int a, int b){
return a > b ? a : b;
}
int height(struct avl *t){
if (!t)
return -1;
else return t->height;
}
struct avl *SingleRotationWithLeft(struct avl *t){
struct avl *k;
k = t->left;
t->left = k->right;
k->right = t;
t->height = max(height(t->left), height(t->right)) + 1;
k->height = max(height(k->left), height(k->right)) + 1;
return k;
}
struct avl *SingleRotationWithRight(struct avl *t){
struct avl *k;
k = t->right;
t->right = k->left;
k->left = t;
t->height = max(height(t->left), height(t->right)) + 1;
k->height = max(height(k->left), height(k->right)) + 1;
return k;
}
struct avl *DoubleRotationWithLeft(struct avl *t){
t->left = SingleRotationWithRight(t->left);
t = SingleRotationWithLeft(t);
return t;
}
struct avl *DoubleRotationWithRight(struct avl *t){
t->right = SingleRotationWithLeft(t->right);
t = SingleRotationWithRight(t);
return t;
}
struct avl* Insert(int num, struct avl *t){
if (!t){
t = new struct avl;
t->num = num;
t->height = 0;
t->left = t->right = NULL;
}
else if (t->num > num){
t->left = Insert(num, t->left);
if (height(t->left) - height(t->right) > 1)
if (t->left->num > num)
t = SingleRotationWithLeft(t);
else t = DoubleRotationWithLeft(t);
t->height = max(height(t->right), height(t->left)) + 1;
}
else if (t->num < num){
t->right = Insert(num, t->right);
if (height(t->right) - height(t->left)>1)
if (t->right->num < num)
t = SingleRotationWithRight(t);
else t = DoubleRotationWithRight(t);
t->height = max(height(t->right), height(t->left)) + 1;
}
return t;
}
int main(){
int n;
freopen("1.in", "r", stdin);
scanf("%d", &n);
int i,num;
struct avl *t = NULL;
for (i = 0; i < n; i++){
scanf("%d", &num);
t = Insert(num, t);
}
if (t)
printf("%d\n", t->num);
return 0;
}