这道题类似1123题。
#include <cstdio>
#include <algorithm>
struct node{
int key;
node* left = nullptr;
node* right = nullptr;
};
int N, t;
node* root = nullptr;
int getHeight(node* r){
if(!r){
return 0;
}
return std::max(getHeight(r->left), getHeight(r->right)) + 1;
}
node* LLRotation(node* r){
node* tmp = r->left;
r->left = r->left->right;
tmp->right = r;
return tmp;
}
node* RRRotation(node* r){
node* tmp = r->right;
r->right = r->right->left;
tmp->left = r;
return tmp;
}
node* LRRotation(node* r){
r->left = RRRotation(r->left);
return LLRotation(r);
}
node* RLRotation(node* r){
r->right = LLRotation(r->right);
return RRRotation(r);
}
node* insertKey(node* r, int key){
if(!r){
node* tmp = new node;
tmp->key = key;
r = tmp;
return r;
}
if(key < r->key){
r->left = insertKey(r->left, key);
if(getHeight(r->left) - getHeight(r->right) == 2){
if(key < r->left->key){
r = LLRotation(r);
} else{
r = LRRotation(r);
}
}
} else{
r->right = insertKey(r->right, key);
if(getHeight(r->right) - getHeight(r->left) == 2){
if(key < r->right->key){
r = RLRotation(r);
} else{
r = RRRotation(r);
}
}
}
return r;
}
int main(){
scanf("%d", &N);
for(int i = 0; i < N; ++i){
scanf("%d", &t);
root = insertKey(root, t);
}
printf("%d", root->key);
return 0;
}
题目如下:
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