探秘数据结构中的红黑树

探索数据结构里的红黑树

红黑树基础

  • 1.红黑树概览
    • 1.1红黑树的界定
      红黑树是一种二叉搜索树,其每个节点额外增设一个存储位用以标识颜色,颜色可分为红色与黑色。通过对从根节点到任意叶子节点路径上各节点颜色加以约束,使得最长路径长度不超过最短路径长度的2倍,近似达成平衡状态。
      此处为图片描述
    • 1.2红黑树的规范
    • 每个节点不是红色就是黑色;
    • 根节点的颜色必定是黑色;
    • 若一个节点为红色,那么它的两个子节点均为黑色,即任意路径中不会出现连续的红色节点;
    • 从任意节点出发,到其所有空节点的简单路径上,所包含的黑色节点数量是相同的。最长路径(由一黑一红节点构成)长度不超过最短路径(全黑节点构成)长度的2倍(以上四条规则对红黑树进行约束)。这里所说的数路径,要将空节点(NIL节点)计算在内。
    • 1.3红黑树的效能
      最短路径长度约为logN,最长路径长度至多为2倍的logN,所以其时间复杂度为O(logN)。

红黑树的实现

2.1红黑树的插入操作

(插入红色节点时,遵循二叉搜索树的规则以及红黑树的四条规则)

2.1.1 情形1:颜色变更

当当前节点(c)为红色、父节点(p)为红色、祖父节点(g)为黑色,且叔叔节点存在并为红色时,将父节点和叔叔节点变为黑色,祖父节点变为红色。然后把祖父节点当作新的当前节点,继续向上更新颜色状态。情况1仅涉及颜色变更,无需进行旋转操作。所以不管当前节点是父节点的左子节点还是右子节点,父节点是祖父节点的左子节点还是右子节点,都是采用上述的颜色变更处理方式。

2.1.2 情形2:单旋转配合颜色变更

当当前节点(c)为红色、父节点(p)为红色、祖父节点(g)为黑色,且叔叔节点不存在或者叔叔节点存在但为黑色时,如果叔叔节点不存在,那么当前节点必定是新插入的节点;如果叔叔节点存在且为黑色,那么当前节点之前必然是黑色,是在当前节点的子树中进行插入操作,符合情形1的情况,通过颜色变更将当前节点从黑色转为红色,然后向上更新。

2.1.3 情形3:双旋转配合颜色变更

当当前节点(c)为红色、父节点(p)为红色、祖父节点(g)为黑色,且叔叔节点不存在或者叔叔节点存在但为黑色时,如果叔叔节点不存在,那么当前节点必定是新插入的节点;如果叔叔节点存在且为黑色,那么当前节点之前必然是黑色,是在当前节点的子树中进行插入操作,符合情形1的情况,通过颜色变更将当前节点从黑色转为红色,然后向上更新。

2.2红黑树的插入代码实现

//test.cpp
#include<iostream>
#include<vector>

using namespace std;

#include"RBTree.h"

//void TestRBTree1()
//{
//    RBTree<int, int> t;
//    // 常规的测试用例
//    //int a[] = { 16, 3, 7, 11, 9, 26, 18, 14, 15 };
//    // 特殊的带有双旋场景的测试用例
//    int a[] = { 4, 2, 6, 1, 3, 5, 15, 7, 16, 14,3,5,66,33,543,54,2,435,321,32,43,4324,534 };
//    for (auto e : a)
//    {
//        t.Insert({ e, e });
//    }
//
//    t.InOrder();
//    cout << t.IsBalanceTree() << endl;
//}
//
//// 插入一堆随机值,测试平衡,顺便测试一下高度和性能等
//void TestRBTree2()
//{
//    const int N = 10000000;
//    vector<int> v;
//    v.reserve(N);
//    srand(time(0));
//
//    for (size_t i = 0; i < N; i++)
//    {
//        v.push_back(rand() + i);
//    }
//
//    size_t begin2 = clock();
//    RBTree<int, int> t;
//    for (auto e : v)
//    {
//        t.Insert(make_pair(e, e));
//    }
//    size_t end2 = clock();
//
//    cout << "Insert:" << end2 - begin2 << endl;
//    cout << t.IsBalanceTree() << endl;
//
//    cout << "Height:" << t.Height() << endl;
//    cout << "Size:" << t.Size() << endl;
//
//    size_t begin1 = clock();
//    // 确定在的值
//    /*for (auto e : v)
//    {
//            t.Find(e);
//    }*/
//
//    // 随机值
//    for (size_t i = 0; i < N; i++)
//    {
//        t.Find((rand() + i));
//    }
//
//    size_t end1 = clock();
//
//    cout << "Find:" << end1 - begin1 << endl;
//}

#include"mymap.h"
#include"myset.h"

int main()
{
    //TestRBTree2();
    bit::test_set();
    bit::test_map();

    return 0;
}
//RBTree.h
enum Colour { RED, BLACK };

// 红黑树节点定义
template<class T>
struct RBTreeNode {
    T _data;
    RBTreeNode<T>* _left;
    RBTreeNode<T>* _right;
    RBTreeNode<T>* _parent;
    Colour _col;

    RBTreeNode(const T& data)
        : _data(data)
        , _left(nullptr)
        , _right(nullptr)
        , _parent(nullptr)
        , _col(RED) {}
};

template<class K, class T, class KeyOfT>
class RBTree {
    typedef RBTreeNode<T> Node;
public:
    bool Insert(const T& data) {
        if (_root == nullptr) {
            _root = new Node(data);
            _root->_col = BLACK;
            return true;
        }

        KeyOfT kot;
        Node* parent = nullptr;
        Node* cur = _root;
        while (cur) {
            if (kot(cur->_data) < kot(data)) {
                parent = cur;
                cur = cur->_right;
            } else if (kot(cur->_data) > kot(data)) {
                parent = cur;
                cur = cur->_left;
            } else {
                return false;
            }
        }

        cur = new Node(data);
        cur->_col = RED;

        if (kot(parent->_data) < kot(data)) {
            parent->_right = cur;
        } else {
            parent->_left = cur;
        }
        cur->_parent = parent;

        while (parent && parent->_col == RED) {
            Node* grandfather = parent->_parent;
            if (parent == grandfather->_left) {
                Node* uncle = grandfather->_right;

                if (uncle && uncle->_col == RED) {
                    parent->_col = uncle->_col = BLACK;
                    grandfather->_col = RED;

                    cur = grandfather;
                    parent = cur->_parent;
                } else {
                    if (cur == parent->_left) {
                        RotateR(grandfather);
                        parent->_col = BLACK;
                        grandfather->_col = RED;
                    } else {
                        RotateL(parent);
                        RotateR(grandfather);

                        cur->_col = BLACK;
                        grandfather->_col = RED;
                    }

                    break;
                }
            } else {
                Node* uncle = grandfather->_left;

                if (uncle && uncle->_col == RED) {
                    parent->_col = uncle->_col = BLACK;
                    grandfather->_col = RED;

                    cur = grandfather;
                    parent = cur->_parent;
                } else {
                    if (cur == parent->_right) {
                        RotateL(grandfather);
                        parent->_col = BLACK;
                        grandfather->_col = RED;
                    } else {
                        RotateR(parent);
                        RotateL(grandfather);

                        cur->_col = BLACK;
                        grandfather->_col = RED;
                    }

                    break;
                }
            }
        }

        _root->_col = BLACK;

        return true;
    }

    void InOrder() {
        _InOrder(_root);
        cout << endl;
    }

    int Height() {
        return _Height(_root);
    }

    int Size() {
        return _Size(_root);
    }

    Node* Find(const K& key) {
        KeyOfT kot;
        Node* cur = _root;
        while (cur) {
            if (kot(cur->_data) < key) {
                cur = cur->_right;
            } else if (kot(cur->_data) > key) {
                cur = cur->_left;
            } else {
                return cur;
            }
        }

        return nullptr;
    }

private:
    int _Size(Node* root) {
        return root == nullptr ? 0 : _Size(root->_left) + _Size(root->_right) + 1;
    }

    int _Height(Node* root) {
        if (root == nullptr) return 0;
        int leftHeight = _Height(root->_left);
        int rightHeight = _Height(root->_right);
        return leftHeight > rightHeight ? leftHeight + 1 : rightHeight + 1;
    }

    void _InOrder(Node* root) {
        if (root == nullptr) return;
        _InOrder(root->_left);
        cout << root->_kv.first << " ";
        _InOrder(root->_right);
    }

    void RotateR(Node* parent) {
        Node* subL = parent->_left;
        Node* subLR = subL->_right;

        parent->_left = subLR;
        if (subLR) subLR->_parent = parent;

        Node* ppnode = parent->_parent;

        subL->_right = parent;
        parent->_parent = subL;

        if (parent == _root) {
            _root = subL;
            subL->_parent = nullptr;
        } else {
            if (ppnode->_left == parent) {
                ppnode->_left = subL;
            } else {
                ppnode->_right = subL;
            }
            subL->_parent = ppnode;
        }
    }

    void RotateL(Node* parent) {
        Node* subR = parent->_right;
        Node* subRL = subR->_left;

        parent->_right = subRL;
        if (subRL) subRL->_parent = parent;

        Node* ppnode = parent->_parent;

        subR->_left = parent;
        parent->_parent = subR;

        if (parent == _root) {
            _root = subR;
            subR->_parent = nullptr;
        } else {
            if (ppnode->_left == parent) {
                ppnode->_left = subR;
            } else {
                ppnode->_right = subR;
            }
            subR->_parent = ppnode;
        }
    }

private:
    Node* _root = nullptr;
};

2.3红黑树的查找

按照二叉搜索树的逻辑来实现查找操作,其搜索效率可达O(logN)。

2.4红黑树的检查

要牢牢记住红黑树的四条规则来进行检查。

版权声明:程序员胖胖胖虎阿 发表于 2025年9月19日 下午3:20。
转载请注明:探秘数据结构中的红黑树 | 胖虎的工具箱-编程导航

相关文章

暂无评论

暂无评论...