【PAT 甲级】A1066 Root of AVL Tree (25分)

一遍过~只要弄明白AVL树的构造过程,这个题还是很容易A掉的!
没什么坑点。

#include <bits/stdc++.h>
using namespace std;
struct node
{
	int key,height;
	node* left;
	node* right;
};
int num[21];
int getHeight(node* nd)
{
	if(!nd) return 0;
	else return nd->height;
}
int bf(node *a)
{
	return getHeight(a->left)-getHeight(a->right);
}
int Height(node* a,node* b)
{
	return max(getHeight(a),getHeight(b))+1;
}
void L(node* &a)	//left rotation
{
	node* temp=a->right;
	a->right=temp->left;
	temp->left=a;
	a->height=Height(a->left,a->right);
	temp->height=Height(temp->left,temp->right);
	a=temp;
}
void R(node* &a)	//right rotation
{
	node* temp=a->left;
	a->left=temp->right;
	temp->right=a;
	a->height=Height(a->left,a->right);
	temp->height=Height(temp->left,temp->right);
	a=temp;
}
node* insert(node* root,int key)
{
	if(!root)
	{
		root=new node;
		root->key=key;
		root->height=0;
		root->left=NULL;
		root->right=NULL;
	}
	else if(key < root->key)		//insert into the left subtree
	{
		root->left=insert(root->left,key);
		if(bf(root)==2)	//imbalanced
		{
			if(bf(root->left)==1)
			R(root);
			else
			{
				L(root->left);
				R(root);
			}
		}
	}
	else							//insert into the right subtree
	{
		root->right=insert(root->right,key);
		if(bf(root)==-2)
		{
			if(bf(root->right)==1)
			{
				R(root->right);
				L(root);
			}
			else L(root);
		}
	}
	root->height=Height(root->left,root->right);		//update the height;
	return root;
}
int main(void)
{
	int n;
	node* root=NULL;
	scanf("%d",&n);
	for(int i=0;i<n;i++)
	{
		scanf("%d",&num[i]);
		root=insert(root,num[i]); 
	}
	printf("%d",root->key);
} 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值