题目:(PAT)1066. Root of AVL Tree
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cmath>
#include<set>
#include<map>
#include<string>
#include<cstring>
#include<stack>
#include<queue>
#include<vector>
#include<cstdlib>
#define cl(a,b) memset(a,b,sizeof(a));
#define P pair<int,int>
#define X first
#define Y second
#define pb push_back
using namespace std;
const int maxn=100;
const int inf=1<<28;
struct node{
int data;
int hight;
node *lson,*rson;
node(){lson=rson=NULL;hight=0;}
};
int geth(node *root){//计算节点左右的高度差
return root?root->hight:-1;
}
bool isbalanced(node *root){//判断是不是平衡
return abs(geth(root->lson)-geth(root->rson))<2;
}
node* LL(node* root){
node *tmp=root->lson;
root->lson=tmp->rson;
tmp->rson=root;
root->hight=max(geth(root->lson),geth(root->rson))+1;
tmp->hight=max(geth(tmp->lson),geth(tmp->rson))+1;
return tmp;
}
node *RR(node *root){
node *tmp=root->rson;
root->rson=tmp->lson;
tmp->lson=root;
root->hight=max(geth(root->lson),geth(root->rson))+1;
tmp->hight=max(geth(tmp->lson),geth(tmp->rson))+1;
return tmp;
}
node *RL(node *root){
root->rson=LL(root->rson);
return RR(root);
}
node *LR(node *root){
root->lson=RR(root->lson);
return LL(root);
}
node *insert(node *root,int v){
if(root==NULL){
root=new node();
root->data=v;
return root;
}
if(v>root->data){
root->rson=insert(root->rson,v);
if(!isbalanced(root)){
if(v>root->rson->data){
root=RR(root);
}
else {
root=RL(root);
}
}
}
else {
root->lson=insert(root->lson,v);
if(!isbalanced(root)){
if(v<root->lson->data){
root=LL(root);
}
else {
root=LR(root);
}
}
}
root->hight=max(geth(root->lson),geth(root->rson))+1;
return root;
}
int main(){
int n;
scanf("%d",&n);
node *root=NULL;
for(int i=0;i<n;i++){
int v;
scanf("%d",&v);
root=insert(root,v);
}
printf("%d\n",root->data);
return 0;
}