1066. Root of AVL Tree (25)
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.
![](https://www.patest.cn/upload/79_mtxjq1kj3gx.jpg)
![](https://www.patest.cn/upload/79_mtxjqnwja2o.jpg)
![](https://www.patest.cn/upload/79_mtxjr4gyzdg.jpg)
![](https://www.patest.cn/upload/79_mtxjrh51o9y.jpg)
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 ythe root of the resulting AVL tree in one line.
Sample Input 1:5 88 70 61 96 120Sample Output 1:
70Sample Input 2:
7 88 70 61 96 120 90 65Sample Output 2:
88
给定一些数字,生成一棵AVL树,问树根是多少。
做了之前那么多题,不得不说,这题是个奇葩,看了很多人的题解,毫无例外是直接建的avl树,而这样的题竟然只有25分,还是个甲级题。
我不觉得有几个人能在考场上写出这种东西来。。。吓得我好几天没刷题,去好好看了看avl树的要点。
其实平衡树无非就是旋转操作,而最基本的就是左旋和右旋,其他一切变换都是在这个的基础上进行的。
理解了何为avl树以后,直接拿splay的模板,改动一下,过了样例一提交就AC了,看来平衡树我掌握的还不错。。。
#include<cmath>
#include<queue>
#include<string>
#include<vector>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<functional>
using namespace std;
typedef long long LL;
typedef unsigned long long ull;
const int mod = 1e9 + 7;
const int maxn = 2e5 + 10;
int n, root, x;
struct AVL
{
const static int maxn = 1e5 + 10;
int F[maxn], ch[maxn][2], sz;
int H[maxn], A[maxn];
int Node(int f, int x){ H[sz] = 1; A[sz] = x; F[sz] = f; ch[sz][0] = ch[sz][1] = 0; return sz++; }
void clear(){ sz = 1; F[0] = ch[0][0] = ch[0][1] = A[0] = H[0] = 0; }
void Count(int x)
{
H[x] = max(H[ch[x][0]], H[ch[x][1]]) + 1;
}
void rotate(int x, int k)
{
int y = F[x]; ch[y][!k] = ch[x][k]; F[ch[x][k]] = y;
if (F[y]) ch[F[y]][y == ch[F[y]][1]] = x;
F[x] = F[y]; F[y] = x; ch[x][k] = y;
Count(y); Count(x);
}
int up(int x)
{
while (F[x] && F[F[x]])
{
Count(F[x]); Count(F[F[x]]);
if (abs(H[ch[F[F[x]]][0]] - H[ch[F[F[x]]][1]]) == 2)
{
int y = x == ch[F[x]][0], z = F[x] == ch[F[F[x]]][0];
y^z ? (rotate(x, y), rotate(x, z)) : rotate(F[x], y);
}
else x = F[x];
}
while (F[x]) { Count(x); x = F[x]; }
return x;
}
void insert(int &x, int y)
{
if (!x) { x = Node(0,y); return; }
for (int i = x; i; i = ch[i][y > A[i]])
{
if (!ch[i][y > A[i]])
{
ch[i][y > A[i]] = Node(i, y);
x = up(ch[i][y > A[i]]);
break;
}
}
}
}solve;
int main()
{
scanf("%d", &n);
solve.clear();
while (n--)
{
scanf("%d", &x);
solve.insert(root, x);
}
printf("%d\n", solve.A[root]);
return 0;
}