0
点赞
收藏
分享

微信扫一扫

PAT 甲级 1066  Root of AVL Tree


1066 Root of AVL Tree (25 point(s))

An AVL tree is a self-balancing binary search tree. In an AVL tree, the heights of the two child subtrees of any node differ by at most one; if at any time they differ by more than one, rebalancing is done to restore this property. Figures 1-4 illustrate the rotation rules.

 

PAT 甲级 1066  Root of AVL Tree_PAT甲级

 

PAT 甲级 1066  Root of AVL Tree_#include_02

 

PAT 甲级 1066  Root of AVL Tree_Root of AVL Tree_03

 

PAT 甲级 1066  Root of AVL Tree_1066_04

Now given a sequence of insertions, you are supposed to tell the root of the resulting AVL tree.

 

Input Specification:

Each input file contains one test case. For each case, the first line contains a positive integer N (≤20) which is the total number of keys to be inserted. Then N distinct integer keys are given in the next line. All the numbers in a line are separated by a space.

Output Specification:

For each test case, print the root of the resulting AVL tree in one line.

Sample Input 1:

5
88 70 61 96 120

Sample Output 1:

70

Sample Input 2:

7
88 70 61 96 120 90 65

Sample Output 2:

88

经验总结:

这一题是经典的AVL树构造,根据题目所给序列,构造AVL树,构造完成后,输出根结点的值就行啦~(๑•̀ㅂ•́)و✧

AC代码

#include <cstdio>
#include <algorithm>
using namespace std;
struct node
{
int data,height;
node * lchild,* rchild;
node(int v):data(v),height(1),lchild(NULL),rchild(NULL){}
};
int get_height(node *root)
{
if(root==NULL)
return 0;
return root->height;
}
void update_height(node *root)
{
root->height=max(get_height(root->lchild),get_height(root->rchild))+1;
}
int get_balance(node *root)
{
return get_height(root->lchild)-get_height(root->rchild);
}
void L(node *&root)
{
node * temp=root->rchild;
root->rchild=temp->lchild;
temp->lchild=root;
update_height(root);
update_height(temp);
root=temp;
}
void R(node *&root)
{
node * temp=root->lchild;
root->lchild=temp->rchild;
temp->rchild=root;
update_height(root);
update_height(temp);
root=temp;
}
void insert(int data,node *&root)
{
if(root==NULL)
{
root=new node(data);
return ;
}
if(data<root->data)
{
insert(data,root->lchild);
update_height(root);
if(get_balance(root)==2)
if(get_balance(root->lchild)==1)
R(root);
else
{
L(root->lchild);
R(root);
}
}
else
{
insert(data,root->rchild);
update_height(root);
if(get_balance(root)==-2)
if(get_balance(root->rchild)==-1)
L(root);
else
{
R(root->rchild);
L(root);
}
}
}
int main()
{
int n,t;
scanf("%d",&n);
node *root=NULL;
for(int i=0;i<n;++i)
{
scanf("%d",&t);
insert(t,root);
}
printf("%d\n",root->data);
return 0;
}

 

举报

相关推荐

0 条评论