题目链接
题目分析
给出一个序列,输出由它构造出的AVL树的根结点值
解题思路
就是 AVL树 的构造过程而已,很简单!
AC程序(C++)
/**********************************
*@ID: 3stone
*@ACM: PAT.A1066 Root of AVL Tree
*@Time: 18/8/16
*@IDE: VSCode 2018 + clang++
***********************************/
#include<cstdio>
#include<algorithm>
using namespace std;
const int maxn = 25;
struct node{ //数结点
int data;
int height;
node* lchild;
node* rchild;
};
int N; //结点数
int seq[maxn];
node* new_node(int data) {
node* root = new node;
root->data = data;
root->height = 1;
root->lchild = root->rchild = NULL;
return root;
}
//获取树高
int get_height(node* root) {
if(root == NULL) return 0;
return root->height;
}
void update_height(node* root) { //只是修改那内容不需要加引用
root->height = max(get_height(root->lchild), get_height(root->rchild)) + 1;
}
//计算平衡因子
int get_banlance_factor(node* root) {
return get_height(root->lchild) - get_height(root->rchild);
}
//左旋
void L(node* &root) {
node* temp = root->rchild;
root->rchild = temp->lchild;
temp->lchild = root;
update_height(root);
update_height(temp);
root = temp;
}
//右旋
void R(node* &root) {
node* temp = root->lchild;
root->lchild = temp->rchild;
temp->rchild = root;
update_height(root);
update_height(temp);
root = temp;
}
//AVL调整
void AVL_adjust(node* &root) { //root为最近失衡结点
//判断失衡类型,是则调整
if(get_banlance_factor(root) == 2){
if(get_banlance_factor(root->lchild) == 1) { //LL型 - 右旋一次即可
R(root);
} else { //LR型 - 先左子树左旋,再右旋即可
L(root->lchild); //转为LL型
R(root);
}
} else if(get_banlance_factor(root) == -2) {
if(get_banlance_factor(root->rchild) == -1) { //RR型 - 左旋一次
L(root);
} else { //RL型 - 右子树先右旋,再左旋即可
R(root->rchild); //转为RR型
L(root);
}
}
}
//插入
void insert(node* &root, int data_x) {
if(root == NULL){
root = new_node(data_x);
return;
}
if(data_x < root->data) {
insert(root->lchild, data_x);
} else {
insert(root->rchild, data_x);
}
//更新高度
update_height(root);
//判断是否失衡,调整
AVL_adjust(root);
}
int main() {
int data;
while(scanf("%d", &N) != EOF) {
node* root = NULL;
//input
for(int i = 1; i <= N; i++){ //边插入边调整
scanf("%d", &data);
//需要找到距离插入点最近的那个失衡结点
insert(root, data);
}
printf("%d\n", root->data);
}
return 0;
}