您的位置:首页 > 其它

PAT 1066. Root of AVL Tree (25)

2015-09-01 16:07 190 查看
AVL树的练习

#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 lson (rt<<1),L,M
//#define rson (rt<<1|1),M+1,R
#define M ((L+R)>>1)
#define cl(a,b) memset(a,b,sizeof(a));
//#define LL long long
#define P pair<int,int>
#define X first
#define Y second
#define pb push_back
#define fread(zcc)  freopen(zcc,"r",stdin)
#define fwrite(zcc) freopen(zcc,"w",stdout)
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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: