題目鏈接:https://pintia.cn/problem-sets/994805342720868352/problems/994805404939173888
題目描述
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.
輸入
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.C
輸出
For each test case, print the root of the resulting AVL tree in one line.
樣例輸入
5
88 70 61 96 120
樣例輸出
70
代碼
#include<cstdio>
#include<algorithm>
using namespace std;
typedef struct node;
typedef node * tree;
struct node {
int v;
int heigh;
tree L,R;
};
int getheigh(tree root){
if(root==NULL) return 0;
return root->heigh;
}
void updataheigh(tree root){
root->heigh=max(getheigh(root->L),getheigh(root->R))+1;
}
int getBalance(tree root){
return getheigh(root->L)-getheigh(root->R);
}
void L(tree &root){
tree temp;
temp=root->R;
root->R=temp->L;
temp->L=root;
updataheigh(root);
updataheigh(temp);
root=temp;
}
void R(tree &root){
tree temp;
temp=root->L;
root->L=temp->R;
temp->R=root;
updataheigh(root);
updataheigh(temp);
root=temp;
}
void insertt(tree &root,int v){
if(root==NULL){
root=new node;
root->v=v;
root->heigh=1;
root->L=root->R=NULL;
return;
}
if(v<root->v){
insertt(root->L,v);
updataheigh(root);
if(getBalance(root)==2){
if(getBalance(root->L)==1){
R(root);
}
else if(getBalance(root->L)==-1){
L(root->L);
R(root);
}
}
}
else{
insertt(root->R,v);
updataheigh(root);
if(getBalance(root)==-2){
if(getBalance(root->R)==-1){
L(root);
}
else if(getBalance(root->R)==1){
R(root->R);
L(root);
}
}
}
}
int main(){
int n;
scanf("%d",&n);
int x;
tree root;
root=NULL;
for(int i=0;i<n;i++){
scanf("%d",&x);
insertt(root,x);
}
printf("%d\n",root->v);
return 0;
}