#include<iostream>
#include<algorithm>
using namespace std;
/*
AVL
*/
//数据结构
struct node{
node *l;
node *r;
int data,h,bf;
};
//新结点
node* newnode(int x){
node *p=new node();
p->l=p->r=0;
p->h=1;
p->data=x;
return p;
}
//更新高度,平衡因子
void update(node *p){
int l=0,r=0;
if(p->l) l=p->l->h;
if(p->r) r=p->r->h;
p->h=max(l,r)+1;
p->bf=l-r;
}
//左旋
void L(node *&a){
node *b=a->r;
a->r=b->l;
b->l=a;
update(a);
update(b);
a=b;
}
//右旋
void R(node *&a){
node *b=a->l;
a->l=b->r;
b->r=a;
update(a);
update(b);
a=b;
}
//插入结点
void insert(node *&b,int x){
if(!b){
b=newnode(x);
return;
}
if(x<b->data){
insert(b->l,x);
update(b);
if(b->bf==2){
if(b->l->bf==1){//LL
R(b);
}else if(b->l->bf==-1){//LR
L(b->l);
R(b);
}
}
}else{
insert(b->r,x);
update(b);
if(b->bf==-2){
if(b->r->bf==-1){//RR
L(b);
}else if(b->r->bf==1){//RL
R(b->r);
L(b);
}
}
}
}
//建树
node* creat(int*a,int n){
node *root=0;
for (int i = 0; i < n; i++)
{
insert(root,a[i]);
}
return root;
}
int a[30];
int main(){
int n;
cin>>n;
for (int i = 0; i < n; i++)
{
cin>>a[i];
}
node *root=creat(a,n);
cout<<root->data;
return 0;
}
PAT 1066 AVL
最新推荐文章于 2021-02-20 21:46:50 发布