【数据结构】模拟实现红黑树(RBTree)的插入算法

1、红黑树基本概念

含义:

首先红黑树是一棵二叉搜索树,它在每一个节点上增加了一个存储位来表示节点的颜色(red 或 black)。红黑树通过对任何一条从根节点到叶子节点简单路径上的颜色来约束,红黑树保证最长路径不超过最短路径的两倍,因而近似平衡,而且在实际应用中发现红黑树性能确实比AVL树性能高。

【数据结构】二叉搜索树的插入,删除,查找等基本操作的实现

【数据结构】AVL树的平衡化旋转及实现AVL树的插入操作

性质:
  1. 每个节点不是黑色就是红色
  2. 树的根节点是黑色的
  3. 如果一个节点是红色的,则它的两个孩子节点是黑色的(没有两个连续的红色节点)
  4. 对于每个节点,从该节点到其所有后代叶子节点的简单路径上,均包含相同数目的黑色节点(每条路径上黑色节点的数量相等)
  5. 每个叶子节点都是黑色的(此处的叶子节点指的是空节点)

【例】:

这里写图片描述


2、插入算法解析

在给已经平衡的RBTree树插入新节点时,有可能会导致树不满足红黑树的性质,这时候就需要重新调整树(节点颜色,树的旋转化等操作)。

又因为红黑树的性质里对于黑色节点的规定较多且根节点也为黑色节点,所以为了简单起见,我们默认新节点为红色节点,不满足性质再调整。

插入新节点大致可以分为五种情况,接下来我们来详细分析这五种情况:

情况一:

若树为空,插入后违反性质二,需要将新增节点颜色改为黑色。

这里写图片描述

情况二:

插入节点父节点为黑色,不违反任何性质,直接插入。

这里写图片描述

情况三

约定:pCur 为当前节点,pParent 为当前节点的父母节点,grand 为当前节点的祖父节点(当前节点父母节点的父母节点),uncle当前节点的父母节点的兄弟节点

【场景】:pCur为红色节点,pParent为红色节点,grand为黑色节点,uncle存在且为红色节点。

这里写图片描述

【解决方式】:

将pParent 和 uncle改成黑色节点;

若grand为根节点,则不用再处理;

若grand不为根节点,则令grand为红色节点,然后把grand 当成pCur,继续朝上更新;

情况四

约定:pCur 为当前节点,pParent 为当前节点的父母节点,grand 为当前节点的祖父节点(当前节点父母节点的父母节点),uncle当前节点的父母节点的兄弟节点

【场景】:pCur节点颜色为红色,pParent节点颜色为红,grand节点颜色为黑,uncle不存在 或是 uncle为黑色。

【解决方式】:

若pParent为grand的左孩子,pCur为pParent的左孩子,则进行右单旋转;

若pParent为grand的右孩子,pCur为pParent的右孩子,则进行左单旋转;

最后令pParent颜色变为黑色,grand颜色变为红色;

这里写图片描述

【注意】:
当uncle不存在时,此时的树每个支路的黑色节点个数是相等的,说明pCur是新插入的节点。

当uncle存在时,因为此时树的各支路黑色节点个数不等,所以此时的pCur不是新节点,而是调整后被改为红色,例如情况三中的图例所示。

情况五:

约定:pCur 为当前节点,pParent 为当前节点的父母节点,grand 为当前节点的祖父节点(当前节点父母节点的父母节点),uncle当前节点的父母节点的兄弟节点

【场景】:pCur节点颜色为红,pParent节点颜色为红,grand节点颜色为黑,uncle节点不存在 或是 uncle节点颜色为黑。

【解决方式】:

若pParent为grand的左孩子,pCur为pParent的右孩子,则针对pParent进行左单旋转;

若pParent为grand的右孩子,pCur为pParent的左孩子,则针对pParent进行右单旋转;

之后树的情况会变成情况四。

这里写图片描述


3、插入算法实现

基本步骤:
  • 若为空树,则创建一个新节点,令根指向这个新节点,并更新节点颜色为黑(性质2);
  • 查找当前节点的插入位置 —-按照二叉搜索树的查找方式
  • 插入新节点
  • 更新节点颜色(之前的插入分析—-五种基本情况)
源码:

RBTree.h:

#pragma once
#include<stdio.h>
#include<iostream>

using namespace std;
enum Color
{
    RED,
    BLACK
};

template<class K,class V>
struct RBTreeNode{
public:
    RBTreeNode(const K& key,const V& value,Color color = RED)
        :_pLeft(NULL)
        , _pRight(NULL)
        , _pParent(NULL)
        , _value(key,value)
        , _color(color)
    {}

public:
    RBTreeNode<K,V>* _pLeft;
    RBTreeNode<K, V>* _pRight;
    RBTreeNode<K, V>* _pParent;
    Color _color;
    pair<K,V> _value;
};

template<class K,class V>
class RBTree{
    typedef RBTreeNode<K, V> Node;
    typedef Node* pNode;
public:
    RBTree()
        :_pRoot(NULL)
    {}

    //插入
    bool InsertUnique(const pair<K,V>& value){
        return _InsertUnique(_pRoot,value);
    }

    //中序遍历
    void InOder(){
        cout << "中序遍历:" << endl;
        _InOder(_pRoot);
    }

    //判断是否是RBTree
    bool IsRBTree(){
        if (NULL == _pRoot)
            return true;
        size_t blackCount = 0;
        size_t count = 0;
        pNode pCur = _pRoot;
        //统计单支路黑色节点个数
        while (pCur){
            if (BLACK == pCur->_color)
                blackCount++;
            pCur = pCur->_pLeft;
        }
        return _IsRBTree(_pRoot, count, blackCount);
    }

protected:

    //判断是否是RBTree
    bool _IsRBTree(pNode pRoot, size_t count, const size_t blackCount){
        if (NULL == pRoot)
            return true;
        if (BLACK == pRoot->_color)
            count++;

        pNode pParent = pRoot->_pParent;
        if (pParent && pParent->_color == RED && pRoot->_color == RED){
            cout << "违反了性质3:不能有两个连续的红色节点" << endl;
            return false;
        }

        if (NULL == pRoot->_pLeft && NULL == pRoot->_pRight){
            if (count != blackCount){
                cout << "违反了性质4:每条路径上黑色节点的数量相等" << endl;
                return false;
            }
        }
        return _IsRBTree(pRoot->_pLeft, count, blackCount) && _IsRBTree(pRoot->_pRight, count, blackCount);
    }

    //中序遍历
    void _InOder(pNode pRoot){
        if (NULL == pRoot){
            return;
        }
        _InOder(pRoot->_pLeft);
        cout << "<" << pRoot->_value.first << "," << pRoot->_value.second << ">" << endl;
        _InOder(pRoot->_pRight);
    }

    //插入操作
    bool _InsertUnique(pNode& pRoot, const pair<K,V>& value){
        if (NULL == pRoot){
            //为空树,情况一
            pRoot = new Node(value.first,value.second);
            pRoot->_color = BLACK;
            return true;
        }
        //查找当前节点的插入位置
        pNode pCur = pRoot;
        pNode pParent = NULL; //标记
        while (pCur){
            if (value.second < pCur->_value.second){
                pParent = pCur;
                pCur = pCur->_pLeft;
            }
            else if (value.second > pCur->_value.second){
                pParent = pCur;
                pCur = pCur->_pRight;
            }
            else{
                //该树数据是不可重复的
                return false;
            }
        }//pCur指向NULL

        //插入新节点
        pCur = new Node(value.first,value.second);
        if (pCur->_value.second > pParent->_value.second){
            pParent->_pRight = pCur;
            pCur->_pParent = pParent;
        }
        else{
            pParent->_pLeft = pCur;
            pCur->_pParent = pParent;
        }

        //更新节点颜色及调整树的结构
        //情况二
        if (BLACK == pParent->_color)
            return true;

        //注意循环条件(因为三种情况下的变色都不会改变cur的颜色,而parent永远都是cur的parent)
        //所以只要parent的颜色为黑即可结束
        while (pParent && RED == pParent->_color){

            //pParent节点的颜色为红,则pParent的父母节点一定存在
            pNode grand = pParent->_pParent;

            if (pParent == grand->_pLeft){

                pNode uncle = grand->_pRight;
                if (uncle && RED == uncle->_color){
                    //情况三
                    pParent->_color = BLACK;
                    uncle->_color = BLACK;
                    grand->_color = RED;
                    if (grand->_pParent && RED == grand->_pParent->_color){
                        //继续朝上更新
                        pCur = grand;
                        pParent = pCur->_pParent;
                    }
                    else{
                        break;
                    }
                }

                if (NULL == uncle || (uncle && BLACK == uncle->_color)){
                    //树需要旋转
                    if (pCur == pParent->_pRight){
                        //情况五
                        RotateL(pParent);
                        swap(pCur, pParent);
                        //继续进行情况四
                    }
                    //情况四
                    RotateR(grand);
                    pParent->_color = BLACK;
                    grand->_color = RED;
                    return true;
                }
            }
            else{
                //pParent为grand的右孩子
                pNode uncle = grand->_pLeft;
                if (uncle && RED == uncle->_color){
                    //情况三的镜像
                    pParent->_color = BLACK;
                    uncle->_color = BLACK;
                    grand->_color = RED;
                    if (grand->_pParent && RED == grand->_pParent->_color){
                        //继续朝上更新
                        pCur = grand;
                        pParent = pCur->_pParent;
                    }
                    else{
                        break;
                    }
                }
                if (NULL == uncle || (uncle && BLACK == uncle->_color)){
                    //需要旋转
                    if (pCur == pParent->_pLeft){
                        //情况五,镜像
                        RotateR(pParent);
                        swap(pCur, pParent);
                    }
                    //情况四
                    RotateL(grand);
                    pParent->_color = BLACK;
                    grand->_color = RED;
                }
            }
        }
        //统一更新根节点颜色
        pRoot->_color = BLACK;
    }

    //左单旋
    void RotateL(pNode pParent){
        if (NULL == pParent)
            return;

        pNode ptr = pParent;
        pNode pSubR = ptr->_pRight;
        pNode pSubRL = pSubR->_pLeft;


        //标记ptr的父母节点
        pNode pPParent = ptr->_pParent;
        //令ptr成为pSubR的左子树
        pSubR->_pLeft = ptr;
        ptr->_pParent = pSubR;

        //pSubRL的值是小于pSubR的值,大于ptr的值,所以可以令pSubRL作为ptr的右子树
        ptr->_pRight = pSubRL;
        if (pSubRL)
            pSubRL->_pParent = ptr;

        pSubR->_pParent = pPParent;

        //判断ptr上一节点的三种情况
        if (NULL == pPParent){
            //ptr为根节点
            _pRoot = pSubR;
        }
        else{
            if (ptr == pPParent->_pLeft)
                pPParent->_pLeft = pSubR;
            else
                pPParent->_pRight = pSubR;
        }

    }

    //右单旋
    void RotateR(pNode pParent){
        if (NULL == pParent)
            return;
        pNode ptr = pParent;
        pNode pSubL = ptr->_pLeft;
        pNode pSubLR = pSubL->_pRight;

        //标记ptr的父母节点
        pNode pPParent = ptr->_pParent;
        //令ptr成为pSubL的左子树
        pSubL->_pRight = ptr;
        ptr->_pParent = pSubL;

        //pSubLR的值是大于pSubL的值,小于ptr的值,所以可以令pSubLR作为ptr的左子树
        ptr->_pLeft = pSubLR;
        if (pSubLR)
            pSubLR->_pParent = ptr;

        pSubL->_pParent = pPParent;

        //判断ptr上一节点的三种情况
        if (NULL == pPParent){
            //ptr为根节点
            _pRoot = pSubL;
        }
        else{
            if (ptr == pPParent->_pLeft)
                pPParent->_pLeft = pSubL;
            else
                pPParent->_pRight = pSubL;
        }

    }

private:
    pNode _pRoot;
};

test.cpp:

#include<Windows.h>
#include<stdio.h>
#include<stdlib.h>
#include<iostream>
#include"RBTree.h"

using namespace std;

//RBTree
void test4(){
    int a[] = { 10, 7, 8, 15, 5, 6, 11, 13, 12 };
    RBTree<int, int> rbtree;
    for (size_t i = 0; i < sizeof(a) / sizeof(a[0]); ++i){
        rbtree.InsertUnique(make_pair(i, a[i]));
    }
    //测试该红黑树是否满足二叉搜索树的性质
    rbtree.InOder();

    //测试树是否满足红黑树的基本性质
    if (rbtree.IsRBTree())
        cout << "该树满足红黑树的基本性质" << endl;

    else
        cout << "该树不满足红黑树的基本性质" << endl;

}

int main(){
    test4();
    system("pause");
    return 0;
}

程序运行结果:

这里写图片描述


4、红黑树的应用思考

模拟实现一个加入迭代器的红黑树
模拟实现一个map(使用红黑树实现)
模拟实现一个set(使用红黑树实现)
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值