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
题意:建AVL,对标1123题,比1123题简单很多,直接莽吧~
#include<iostream>
#include<vector>
using namespace std;
struct node{
int data;
struct node * lchild;
struct node * rchild;
};
node * ll_rotate(node * t){
node * t_r = t -> rchild;
t -> rchild = t_r -> lchild;
t_r -> lchild = t;
return t_r;
}
node *rr_rotate(node * t){
node * t_l = t -> lchild;
t -> lchild = t_l -> rchild;
t_l -> rchild = t;
return t_l;
}
node * rl_rotate(node * t){
t -> rchild = rr_rotate(t -> rchild);
return ll_rotate(t);
}
node * lr_rotate(node * t){
t -> lchild = ll_rotate(t -> lchild);
return rr_rotate(t);
}
int height(node * t){
if(t == NULL){
return 0;
}
int l = height(t -> lchild);
int r = height(t -> rchild);
return l > r ? l + 1 : r + 1;
}
node * creat_tree(node * root, int data){
if(root == NULL){
root = new node();
root -> data = data;
root -> lchild = root -> rchild = NULL;
}else if (root -> data > data) //左
{
root -> lchild = creat_tree(root -> lchild, data);
int l = height(root -> lchild);
int r = height(root -> rchild);
if((l - r) > 1){
if(height(root -> lchild -> lchild) > height(root -> lchild -> rchild)){
root = rr_rotate(root);
}else
{
root = lr_rotate(root);
}
}
}else //右
{
root -> rchild = creat_tree(root -> rchild, data);
int l = height(root -> lchild);
int r = height(root -> rchild);
if((r - l) > 1){
if(height(root -> rchild -> lchild) < height(root -> rchild -> rchild)){
root = ll_rotate(root);
}else
{
root = rl_rotate(root);
}
}
}
return root;
}
int main(){
int n;
cin >> n;
node * tree = NULL;
for(int i = 0; i < n; i++){
int temp;
scanf("%d", &temp);
tree = creat_tree(tree, temp);
}
printf("%d\n", tree -> data);
return 0;
}