_07-AVL树节点的调整

题意:

本题你需要处理AVL树的四种情况,分别是RR、RL、LL和LR。

注意:本题不仅需要正确设置子节点,也需要你正确处理父节点,还需要你正确维护height也就是树高字段,判分模板会根据你的height来判断平衡是否满足要求。

 思路:

①对于RR、LL型。 以RR型为例,被破坏节点记为node,其右儿子记为t。首先先将node右儿子变为t的左儿子,若t的左儿子非空,将其父节点设为node,再将t的左儿子指向node。然后先将t的父节点由原本的node变为node的父节点,再将node的父节点变为t,在做完这两个父节点的转化后,容易忘记对t现在的父节点的调整。对t的父节点进行一个判空,若不为空则将其左儿子或者右儿子指向t。最后再对t和node的高度调整一下即可。LL型与RR相似,在此不赘述。

②对于LR、RL型。只需借用RR、LL型旋转即可,这里以RL为例。先将t作为被破坏点传入LL型旋转中,LL旋转完后则会变成以node为被破坏点的RR型,这时将node传入RR型旋转函数中即可。

源码:

#include <algorithm>
//struct BTreeNode{
//    int value{0};
//    int height{0};
//    BTreeNode* parent{nullptr};
//    BTreeNode* left_child{nullptr};
//    BTreeNode* right_child{nullptr};
//    BTreeNode( int value ){
//        this->value = value;
//    }
//    BTreeNode(){
//        this->value = 0;
//    }
//};
//

int h(BTreeNode * node) {  //获取树高度函数
    if (!node)
        return -1;
    else
        return node->height;
}
void rotate_rr(BTreeNode* node) {
    if (!node) return;  //对树判空
    BTreeNode* t = node->right_child;
    node->right_child = t->left_child;
    if (t->left_child)
        t->left_child->parent = node;
    t->parent = node->parent;
    if (t->parent)
        if (t->parent->left_child == node)  //将t父节点的左或右儿子指向node
            t->parent->left_child = t;
        else
            t->parent->right_child = t;
    node->parent = t;
    t->left_child = node;
    node->height = max(h(node->left_child), h(node->right_child)) + 1;  //获取高度
    t->height = max(h(t->left_child), h(t->right_child)) + 1;
}
void rotate_ll(BTreeNode* node) {
    if (!node) return;  //对树判空
    BTreeNode* t = node->left_child;
    node->left_child = t->right_child;
    if (t->right_child)
        t->right_child->parent = node;
    t->parent = node->parent;
    if (t->parent)
        if (t->parent->left_child == node)//将t父节点的左或右儿子指向node
            t->parent->left_child = t;
        else
            t->parent->right_child = t;
    node->parent = t;
    t->right_child = node;
    node->height = max(h(node->left_child), h(node->right_child)) + 1;
    t->height = max(h(t->left_child), h(t->right_child)) + 1;
}
void rotate_rl(BTreeNode* node) {
    BTreeNode* t = node->right_child;
    rotate_ll(t);
    rotate_rr(node);
}
void rotate_lr(BTreeNode* node) {
    BTreeNode* t = node->left_child;
    rotate_rr(t);
    rotate_ll(node);
}

ps:对于RR、LL型,以RR型为例。不管t的左儿子是否空,都要先将其成为node的右儿子,然后再判空,来决定是否要调整t左儿子的父节点;在t的父节点调整为node的父节点后,还要对调整后的t父节点判空,来决定是否要调整其左或右儿子指向t。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

别搜了,自己做

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值