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

AVL

1. 原文

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.

img

img img

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:

1
2
5
88 70 61 96 120

Sample output 1:

1
70

Sample Input 2:

1
2
7
88 70 61 96 120 90 65

Sample output 2:

1
88

2. 解析

AVL 套路

3. AC代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#include<cstdio>
#include<algorithm>
using namespace std;
struct node
{
int data,height;
node *lchild,*rchild;
};
node* newNode(int x){
node* root=new node;
root->data=x;
root->height=1;
root->lchild=root->rchild=NULL;
return root;
}
int getHeight(node *root){
if (root==NULL)
{
return 0;
}else{
return root->height;
}
}
int getFactor(node* root){
return getHeight(root->lchild)-getHeight(root->rchild);
}
void update(node* &root){
root->height=max(getHeight(root->lchild),getHeight(root->rchild))+1;
}
void L(node* &root){
node* temp=root->rchild;
root->rchild=temp->lchild;
temp->lchild=root;
update(root);
update(temp);
root=temp;
}
void R(node* &root){
node* temp=root->lchild;
root->lchild=temp->rchild;
temp->rchild=root;
update(root);
update(temp);
root=temp;
}
void create(node* &root,int x){
if (root==NULL)
{
root=newNode(x);
}else if(root->data>x){
create(root->lchild,x);
update(root);
if (getFactor(root)==2)
{
if(getFactor(root->lchild)==1){
R(root);
}else if(getFactor(root->lchild)==-1){
L(root->lchild);
R(root);
}
}
}else{
create(root->rchild,x);
update(root);
if (getFactor(root)==-2)
{
if (getFactor(root->rchild)==-1)
{
L(root);
}else if(getFactor(root->rchild)==1){
R(root->rchild);
L(root);
}
}
}
}
int main()
{
int n;
scanf("%d",&n);
int a;
node *root=NULL;
for (int i = 0; i < n; ++i)
{
scanf("%d",&a);
create(root,a);
}
printf("%d\n",root->data);
return 0;
}
本文结束  感谢您的阅读
  • 本文作者: Wang Ting
  • 本文链接: /zh-CN/2019/09/03/A1066/
  • 发布时间: 2019-09-03 12:33
  • 更新时间: 2021-10-29 14:03
  • 版权声明: 本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!