分析:AVL树常规操作,靠着模糊的记忆和临时的推导把代码写了个大概,但是由于忘了要用引用将旋转后的结点返回导致没过样例,代码还是比较简洁的,可以作为AVL树的模板了。AVL树其实在理解了BST后就比较好理解和推导了,至于旋转过程自己在纸上也比较简单能推出。
#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
struct Tree{
int data;
struct Tree *l, *r;
};
int getH(Tree *root){
if(!root) return 0;
return max(getH(root->l), getH(root->r))+1;
}
int getBF(Tree *root){ //获取平衡因子Balanced Factor
return getH(root->l)-getH(root->r);
}
//左旋
void LL(Tree* &root){ //需要引用将root返回
Tree *tem = root->r;
root->r = tem->l;
tem->l = root;
root = tem;
}
//右旋
void RR(Tree* &root){
Tree *tem = root->l;
root->l = tem->r;
tem->r = root;
root = tem;
}
Tree * create(Tree *root, int data){
if(!root){
root = new Tree;
root->data = data;
root->l = root->r = NULL;
root->height = 1;
return root;
}
if(data < root->data){
root->l = create(root->l, data);
if(getBF(root) == 2){
if(getBF(root->l) == 1){
RR(root);
} else if(getBF(root->l) == -1){
LL(root->l);
RR(root);
}
}
} else {
root->r = create(root->r, data);
if(getBF(root) == -2){
if(getBF(root->r) == -1){
LL(root);
} else if(getBF(root->r) == 1){
RR(root->r);
LL(root);
}
}
}
return root;
}
int main(){
//freopen("aa.txt", "r", stdin);
int n, num;
cin >> n;
Tree *root = NULL;
for(int i = 0; i<n; i++){
cin >> num;
root = create(root, num);
}
cout << root->data << "\n";
return 0;
}