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(平衡二叉)树,依次给出n个插入结点的权,求建完树后的根节点的权值是多少?
思路:
直接建立一颗AVL树,AVL树比二叉查找树多了一个高度,还有调平衡。
#include<iostream>
using namespace std;
const int maxn=55;
int weight[maxn];
int n;
struct node {
int height;
int data;
node* lchild;
node* rchild;
};
node* newNode(int x){
node* Node=new node;
Node->height=1;//新节点初始化高度为1,空结点高度为0;
Node->data=x;
Node->lchild=NULL;
Node->rchild=NULL;
return Node;
}
int getHeight(node* root){
if(root == NULL) return 0;//空树的高度为0;
return root->height;
}
void updateHeight(node* root){//算出该结点的高度;
root->height = max(getHeight(root->lchild),getHeight(root->rchild)) + 1;
return ;
}
int getBalanceFactor(node* root){//算出该结点的平衡因子;
return getHeight(root->lchild) - getHeight(root->rchild);
}
void L(node* &root){//左旋;
node* temp = root->rchild;
root->rchild = temp->lchild;
temp->lchild = root;
updateHeight(root);//旋转后记得更新旋转后结点的高度;
updateHeight(temp);
root = temp;
}
void R(node* &root){
node* temp = root->lchild;
root->lchild = temp->rchild;
temp->rchild = root;
updateHeight(root);
updateHeight(temp);
root = temp;
}
void insert(node* &root,int x){
if(root == NULL){
root = newNode(x);
return;
}
if(x <root->data){
insert(root->lchild,x);
updateHeight(root);
if(getBalanceFactor(root) == 2){
if(getBalanceFactor(root->lchild) == 1){
R(root);
}
else if(getBalanceFactor(root->lchild) == -1){
L(root->lchild);
R(root);
}
}
}
else{
insert(root->rchild,x);
updateHeight(root);
if(getBalanceFactor(root) == -2){
if(getBalanceFactor(root->rchild) == -1){
L(root);
}
else if(getBalanceFactor(root->rchild) == 1){
R(root->rchild);
L(root);
}
}
}
}
//左旋右旋和插入都是需要改变二叉树结构的,所以需要用到引用;
int main( ){
node* root = NULL;
scanf("%d",&n);
for(int i=0;i<n;i++)scanf("%d",&weight[i]);//pat里面数组尽量不要叫做data;
for(int i=0;i<n;i++){
insert(root,weight[i]);
}
printf("%d",root->data);
return 0;
}