PAT 1066 AVL

#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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值