1066. Root of AVL Tree (25)

1066. Root of AVL Tree (25)

#include <iostream>
using namespace std;
int max(int a,int b)
{
	return a>b?a:b;
}
class AvlTree
{
public:
	struct node
	{
		int value;
		node *left,*right;
		int height;
		node(int v):value(v),left(NULL),right(NULL),height(1){};
	};
	node *root;
	AvlTree(){root=NULL;}
	inline int GetHeight(node *r)
	{
		if(r==NULL) return 0;
		else return r->height;
	}
	inline bool IsBalance(node *r)
	{
		return abs(GetHeight(r->left)-GetHeight(r->right))<2;
	}
	node* Retate_L(node *r)
	{
		node *r1;
		r1=r->left;
		r->left=r1->right;
		r1->right=r;
		r->height=max(GetHeight(r->left),GetHeight(r->right))+1;
		r1->height=max(GetHeight(r1->left),GetHeight(r1->right))+1;
		return r1;
	}
	node* Retate_R(node *r)
	{
		node *r1;
		r1=r->right;
		r->right=r1->left;
		r1->left=r;
		r->height=max(GetHeight(r->left),GetHeight(r->right))+1;
		r1->height=max(GetHeight(r1->left),GetHeight(r1->right))+1;
		return r1;
	}
	node* Retate_LR(node *r)
	{
		r->right=Retate_L(r->right);
		return Retate_R(r);
	}
	node* Retate_RL(node *r)
	{
		r->left=Retate_R(r->left);
		return Retate_L(r);
	}
	node* insert(node *r,int v)
	{
		if(r==NULL)
		{
			r=new node(v);
			return r;
		}
		if(v<r->value)
		{
			r->left=insert(r->left,v);
			r->height=max(GetHeight(r->left),GetHeight(r->right))+1;
			if(!IsBalance(r))
			{
				if(v<r->left->value) r=Retate_L(r);
				else r=Retate_RL(r);
			}
		}
		else
		{
			r->right=insert(r->right,v);
			r->height=max(GetHeight(r->left),GetHeight(r->right))+1;
			if(!IsBalance(r))
			{
				if(v>=r->right->value) r=Retate_R(r);
				else r=Retate_LR(r);
			}
		}
		return r;
	}
	void insert(int v)
	{
		root=insert(root,v);
	}
};
class CA
{
public:
	AvlTree at;
	void run();
};

void CA::run()
{
	int n,t;
	scanf("%d",&n);
	while(n-->0)
	{
		scanf("%d",&t);
		at.insert(t);
	}
	printf("%d\n",at.root->value);
}

int main()
{
//	freopen("test.in","r",stdin);
	CA *a=new CA;
	a->run();
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值