【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);
} 
发布了15 篇原创文章 · 获赞 1 · 访问量 173

猜你喜欢

转载自blog.csdn.net/weixin_42278063/article/details/104652667