7-6 Root of AVL Tree

題目

題意:給定序列建出AVL樹,輸出AVL樹的根結點值

tip:AVL建樹模板

#include<iostream>
using namespace std;
struct node {
	int val;
	struct node *l,*r;
};
struct node* RR(struct node *root)
{
	struct node* t=root->l;
	root->l=t->r;
	t->r=root;
	return t;
}
struct node* LL(struct node *root)
{
	struct node* t=root->r;
	root->r=t->l;
	t->l=root;
	return t;
}
struct node* LR(struct node *root)
{
	root->l=LL(root->l);
	return RR(root);
}
struct node* RL(struct node *root)
{
	root->r=RR(root->r);
	return LL(root);
}
int getdepth(struct node* root)
{
	if(root==NULL)
	return 0;
	return max(getdepth(root->l),getdepth(root->r))+1;
}
struct node* creat(struct node* root,int val)
{
	if(root==NULL)
	{
		root=new node();
		root->val=val;
		root->l=root->r=NULL;
	}
	else if(root->val>val)
	{
		root->l=creat(root->l,val);
		if(getdepth(root->l)-getdepth(root->r)==2)
			root=val<root->l->val?RR(root):LR(root);
	}
	else
	{
		root->r=creat(root->r,val);
		if(getdepth(root->r)-getdepth(root->l)==2)
			root=val>root->r->val?LL(root):RL(root);
	}
	return root;
}
int main()
{
	int n;
	cin>>n;
	struct node *root=NULL;
	for(int i=0;i<n;++i)
	{
		int t;
		cin>>t;
		root=creat(root,t);
	}
	cout<<root->val;
	return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章