题目描述
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.




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
考点
平衡二叉树的插入
思路
如何平衡二叉树
平衡二叉树的失衡调整主要是通过旋转最小失衡子树来实现的。总共有LL、LR、RL、RR四种情况,分别对应右旋、左旋、先右旋再左旋、先左旋再右旋。RL和LR都可以调用LL、RR的代码实现。
代码
#include <iostream>
#include <algorithm>
using namespace std;
typedef struct node {
int data;
struct node *left, *right;
}node;
node *LRotate(node *p) {
node *q = p->right;
p->right = q->left;
q->left = p;
return q;
}
node *RRotate(node *p) {
node *q = p->left;
p->left = q->right;
q->right = p;
return q;
}
node *LRRotate(node *p) {
p->left = LRotate(p->left);
return RRotate(p);
}
node *RLRotate(node *p) {
p->right = RRotate(p->right);
return LRotate(p);
}
int getHeight(node *p) {
if (p == NULL) return 0;
return max(getHeight(p->left), getHeight(p->right)) + 1;
}
node *insert(node *p, int data) {
if (p == NULL) {
p = new node();
p->data = data;
}
else if (p->data > data) {
p->left = insert(p->left, data);
if (abs(getHeight(p->left) - getHeight(p->right)) >= 2) {
if (p->left->data > data) p = RRotate(p);
else p = LRRotate(p);
}
}
else {
p->right = insert(p->right, data);
if (abs(getHeight(p->left) - getHeight(p->right)) >= 2) {
if (p->right->data < data) p = LRotate(p);
else p = RLRotate(p);
}
}
return p;
}
int main() {
int n, i;
cin >> n;
node *p = NULL;
for (i = 0; i < n; i++) {
int d;
cin >> d;
p=insert(p, d);
}
cout << p->data;
return 0;
}