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 ythe 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树模板题。
不要手欠写错就行。
#include <cstdio>
using namespace std;
#include <algorithm>
struct AVLnode{
int value;
int height;
int bf; //balance factor平衡因子
AVLnode* left;
AVLnode* right;
};
AVLnode* root;
void initialize(){
root=NULL;
}
class AVLtree{
public:
/*get结点的高度 */
int getHeight(AVLnode* t){
if(t==NULL) return 0;
else return t->height;
}
/*计算平衡因子 */
int calBF(AVLnode* t){
if(t==NULL) return 0;
else{
int L=getHeight(t->left),R=getHeight(t->right);
return L-R;
}
}
/*
下面是4种旋转。
只要搞清楚LL旋转一种,其他的旋转都很容易写了。
*/
void RotateLL(AVLnode* &k){
AVLnode* k1=k->left;
k->left=k1->right;
k1->right=k;
//update height
k->height=1+max(getHeight(k->left),getHeight(k->right));
k1->height=1+max(getHeight(k1->left),getHeight(k));
//update balance factor
k->bf=calBF(k);
k1->bf=calBF(k1);
k=k1;
}
void RotateRR(AVLnode* &k){
AVLnode* k1=k->right;
k->right=k1->left;
k1->left=k;
k->height=1+max(getHeight(k->left),getHeight(k->right));
k1->height=1+max(getHeight(k),getHeight(k1->right));
k->bf=calBF(k);
k1->bf=calBF(k1);
k=k1;
}
void RotateLR(AVLnode* &k){
RotateRR(k->left);
RotateLL(k);
}
void RotateRL(AVLnode* &k){
RotateLL(k->right);
RotateRR(k);
}
/*往AVL数中插入新结点*/
void Insert(AVLnode* &t,int v){
if(t==NULL){
t=new AVLnode();
t->left=NULL;
t->right=NULL;
t->value=v;
t->height=1;
t->bf=0;
return;
}
else if(v<t->value) Insert(t->left,v);
else Insert(t->right,v);
t->height=1+max(getHeight(t->left),getHeight(t->right));
t->bf=calBF(t);
if(t->bf>1) { //如果左边更重
if(t->left->bf>0) RotateLL(t);
else RotateLR(t);
}
else if(t->bf<-1) { //如果右边更重
if(t->right->bf<0) RotateRR(t);
else RotateRL(t);
}
}
};
int main(){
int N;
scanf("%d",&N);
AVLtree tree;
initialize();
int x;
for(int i=0;i<N;i++){
scanf("%d",&x);
tree.Insert(root,x);
}
if(root!=NULL) printf("%d",root->value);
return 0;
}