【ACM】- PAT. A1066 Root of AVL Tree 【AVL】

12 篇文章 0 订阅
题目链接
题目分析

给出一个序列,输出由它构造出的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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值