跳到主要内容
极客日志极客日志面向AI+效率的开发者社区
首页博客GitHub 精选镜像工具UI配色美学隐私政策关于联系
搜索内容 / 工具 / 仓库 / 镜像...⌘K搜索
注册
博客列表
C++算法

C++ 红黑树实现详解:规则、结构与插入查找验证

综述由AI生成红黑树是一种自平衡二叉搜索树,通过颜色约束确保路径长度不超过最短路径的两倍。详细阐述了红黑树的四条核心规则及其对效率的影响,深入分析了插入操作中的变色、单旋和双旋处理逻辑。内容包括红黑树节点结构设计、插入查找验证的代码实现,并提供了完整的 C++ 源码示例及与 AVL 树的性能对比测试方法。

深海蔚蓝发布于 2026/2/27更新于 2026/6/221 浏览
C++ 红黑树实现详解:规则、结构与插入查找验证

一、红黑树的概念

红黑树是一棵二叉搜索树,它的每个结点增加一个存储位来表示结点的颜色,可以是红色或者黑色。通过对任何一条从根到叶子路径上各个结点的颜色进行约束,红黑树确保没有一条路径会比其他路径长出 2 倍,因而是接近平衡的。

1.1 红黑树的规则

  1. 每个结点不是红色就是黑色
  2. 根结点是黑色的
  3. 如果一个结点是红色的,则它的两个孩子结点必须是黑色的,也就是说任意一条路径不会有连续的红色结点。
  4. 对于任意一个结点,从该结点到其所有 NULL 结点的简单路径上,均包含相同数量的黑色结点(最长路径 <= 2*最短路径)

说明:《算法导论》等书籍上补充了一条每个叶子结点 (NIL) 都是黑色的规则。它这里所指的叶子结点不是传统意义上的叶子结点,而是我们说的空结点,有些书籍上也把 NIL 叫做外部结点。NIL 是为了方便准确地标识出所有路径,《算法导论》在后续讲解实现的细节中也忽略了 NIL 结点,所以我们知道一下这个概念即可。

见下图,为了让上面的第三点规则更闭环一点,补充了当红色节点没有孩子结点的情况,空节点也是黑色的。

文章配图

1.2 思考一下,红黑树如何确保最长路径不超过最短路径的 2 倍的?

  • 由 规则 4 可知,从根到 NULL 结点的每条路径都有相同数量的黑色结点,所以极端场景下,最短路径就是全是黑色结点的路径,假设最短路径长度为 bh(black height)。
  • 由 规则 2 和 规则 3 可知,任意一条路径不会有连续的红色结点,所以极端场景下,最长的路径就是一黑一红间隔组成,那么最长路径的长度为 2*bh。
  • 综合红黑树的 4 点规则而言,理论上的全黑最短路径和一黑一红的最长路径并不是在每棵红黑树都存在的。假设任意一条从根到 NULL 结点路径的长度为 x,那么 bh <= x <= 2*bh。

下面是经典的红黑树,可以根据下图去更好的理解上面红黑树的规则:

文章配图

1.3 红黑树的效率

假设 N 是红黑树树中结点数量,h 最短路径的长度,那么 2^h - 1 <= N < 2^(2h) - 1 , 由此推出 h ≈ logN,也就是意味着红黑树增删查改最坏也就是走最长路径 2logN,那么时间复杂度还是 O(logN)。

红黑树的表达相对 AVL 树要抽象一些,AVL 树通过高度差直观的控制了平衡。红黑树通过 4 条规则的颜色约束,间接的实现了近似平衡,他们效率都是同一档次,但是相对而言,插入相同数量的结点,红黑树的旋转次数是更少的,因为他对平衡的控制没那么严格。

二、红黑树的实现

2.1 红黑树的结构

//枚举值表示颜色
enum Colour { RED, BLACK };
//这里我们默认使用 key/value 结构实现
template<class K,class V>
struct  {
    
    pair<K, V> _kv;
    RBTreeNode<K,V>* _left;
    RBTreeNode<K, V>* _right;
    RBTreeNode<K, V>* _parent;
    Colour _col;
    ( pair<K,V>& kv) :_kv(kv) ,_left() ,_right() ,_parent() { }
};
< , >
  {
     RBTreeNode< ,  > Node;
:
:
    Node* _root;
};
RBTreeNode
// 这里更新控制平衡加入 parent 指针
RBTreeNode
const
nullptr
nullptr
nullptr
template
class
K
class
V
class
RBTree
typedef
class
K
class
V
public
private

2.2 红黑树的插入

【红黑树树插入一个值的大概过程】
  1. 插入一个值按二叉搜索树规则进行插入,插入后我们只需要观察是否符合红黑树的 4 条规则。
  2. 如果是空树插入,新增结点是黑色结点。如果是非空树插入,新增结点必须红色结点,因为非空树插入,新增黑色结点就破坏了规则 4,规则 4 是很难维护的。
  3. 非空树插入后,新增结点必须红色结点,如果父亲结点是黑色的,则没有违反任何规则,插入结束
  4. 非空树插入后,新增结点必须红色结点,如果父亲结点是红色的,则违反规则 3。进一步分析,c 是红色,p 为红,g 必为黑(插入之前保证这棵树是一棵平衡的红黑树),这三个颜色都固定了,关键的变化看 u 的情况,需要根据 u 分为以下几种情况分别处理。

文章配图

说明:下图中假设我们把新增结点标识为 c (cur),c 的父亲标识为 p(parent),p 的父亲标识为 g(grandfather),p 的兄弟标识为 u(uncle)。

【情况 1:变色】

文章配图

c 为红,p 为红,g 为黑,u 存在且为红,则将 p 和 u 变黑,g 变红。在把 g 当做新的 c,继续往上更新。

分析:因为 p 和 u 都是红色,g 是黑色,把 p 和 u 变黑,左边子树路径各增加一个黑色结点,g 再变红,相当于保持 g 所在子树的黑色结点的数量不变,同时解决了 c 和 p 连续红色结点的问题,需要继续往上更新是因为,g 是红色,<1>如果 g 的父亲还是红色,那么就还需要继续处理;<2>如果 g 的父亲是黑色,则处理结束了;<3>如果 g 就是整棵树的根,再把 g 变回黑色。

情况 1 只变色,不旋转。所以无论 c 是 p 的左还是右,p 是 g 的左还是右,都是上面的变色处理方式。

  • 跟 AVL 树类似,图 0 我们展示了一种具体情况,但是实际中需要这样处理的有很多种情况。
  • 图 1 将以上类似的处理进行了抽象表达,d/e/f 代表每条路径拥有 hb 个黑色结点的子树,a/b 代表每 条路径拥有 hb-1 个黑色结点的根为红的子树,hb>=0。
  • 图 2/图 3/图 4,分别展示了 hb == 0/hb == 1/hb == 2 的具体情况组合分析,当 hb 等于 2 时,这里组合情况上百亿种,这些样例是帮助我们理解,不论情况多少种,多么复杂,处理方式一样的,变色再继续往上处理即可,所以我们只需要看抽象图即可。

文章配图 文章配图 文章配图 图 3 文章配图

【情况 2:单旋 + 变色】

c 为红,p 为红,g 为黑,u 不存在或者 u 存在且为黑,u 不存在,则 c 一定是新增结点,u 存在且为黑,则 c 一定不是新增,c 之前是黑色的,是在 c 的子树中插入,符合情况 1,变色将 c 从黑色变成红色,更新上来的。

分析:p 必须变黑,才能解决,连续红色结点的问题,u 不存在或者是黑色的,这里单纯的变色无法解决问题,需要旋转 + 变色。

文章配图

如果 p 是 g 的左,c 是 p 的左,那么以 g 为旋转点进行右单旋,再把 p 变黑,g 变红即可。p 变成这颗树的根,这样子树黑色结点的数量不变,没有连续的红色结点了,且不需要往上更新,因为 p 的父亲是黑色还是红色或者空都不违反规则。

文章配图

如果 p 是 g 的右,c 是 p 的右,那么以 g 为旋转点进行左单旋,再把 p 变黑,g 变红即可。p 变成这颗树新的根,这样子树黑色结点的数量不变,没有连续的红色结点了,且不需要往上更新,因为 p 的父亲是黑色还是红色或者空都不违反规则。

文章配图

【情况 2:双旋 + 变色】

c 为红,p 为红,g 为黑,u 不存在或者 u 存在且为黑,u 不存在,则 c 一定是新增结点,u 存在且为黑,则 c 一定不是新增,c 之前是黑色的,是在 c 的子树中插入,符合情况 1,变色将 c 从黑色变成红色,更新上来的。

分析:p 必须变黑,才能解决,连续红色结点的问题,u 不存在或者是黑色的,这里单纯的变色无法解决问题,需要旋转 + 变色。

文章配图

如果 p 是 g 的左,c 是 p 的右,那么先以 p 为旋转点进行左单旋,再以 g 为旋转点进行右单旋,再把 c 变黑,g 变红即可。c 变成这棵树新的根,这样子树黑色结点的数量不变,没有连续的红色结点了,且 不需要往上更新,因为 c 的父亲是黑色还是红色或者空都不违反规则。

文章配图

如果 p 是 g 的右,c 是 p 的左,那么先以 p 为旋转点进行右单旋,再以 g 为旋转点进行左单旋,再把 c 变黑,g 变红即可。c 变成这颗树新的根,这样子树黑色结点的数量不变,没有连续的红色结点了,且 不需要往上更新,因为 c 的父亲是黑色还是红色或者空都不违反规则。

文章配图

2.3 红黑树的插入代码实现

bool Insert(const pair<K, V>& kv) {
    if (_root == nullptr) {
        _root = new Node(kv);
        _root->_col = BLACK;
        return true;
    }
    Node* parent = nullptr;
    Node* cur = _root;
    while (cur) {
        if (cur->_kv.first < kv.first) {
            parent = cur;
            cur = cur->_right;
        } else if (cur->_kv.first > kv.first) {
            parent = cur;
            cur = cur->_left;
        } else {
            return false;
        }
    }
    cur = new Node(kv);
    cur->_col = RED;
    if (parent->_kv.first < kv.first) {
        parent->_right = cur;
    } else {
        parent->_left = cur;
    }
    cur->_parent = parent;
    while (parent && parent->_col == RED) {
        Node* grandfather = parent->_parent;
        if (grandfather->_left == parent) {
            // g
            // p u
            Node* uncle = grandfather->_right;
            // 情况一:uncle 存在且为红
            if (uncle && uncle->_col == RED) {
                // 变色
                parent->_col = uncle->_col = BLACK;
                grandfather->_col = RED;
                // 继续往上处理
                cur = grandfather;
                parent = cur->_parent;
            } else // 情况二:uncle 不存在,或者存在且为黑
            {
                if (cur == parent->_left) {
                    // 单旋 + 变色
                    // g
                    // p u
                    //c
                    RotateR(grandfather);
                    parent->_col = BLACK;
                    grandfather->_col = RED;
                } else {
                    // 双旋 + 变色
                    // g
                    // p u
                    // c
                    RotateL(parent);
                    RotateR(grandfather);
                    cur->_col = BLACK;
                    grandfather->_col = RED;
                }
                break;
            }
        } else {
            // g
            // u p
            Node* uncle = grandfather->_left;
            // 情况一:叔叔存在且为红,变色即可
            if (uncle && uncle->_col == RED) {
                parent->_col = uncle->_col = BLACK;
                grandfather->_col = RED;
                // 继续往上处理
                cur = grandfather;
                parent = cur->_parent;
            } else // 叔叔不存在,或者存在且为黑
            {
                // 情况二:叔叔不存在或者存在且为黑
                // 单旋 + 变色
                // g
                // u p
                // c
                if (cur == parent->_right) {
                    RotateL(grandfather);
                    parent->_col = BLACK;
                    grandfather->_col = RED;
                } else {
                    //双旋 + 变色
                    // g
                    // u p
                    // c
                    RotateR(parent);
                    RotateL(grandfather);
                    cur->_col = BLACK;
                    grandfather->_col = RED;
                }
                break;
            }
        }
    }
    _root->_col = BLACK;
    return true;
}

2.4 红黑树的查找

按二叉搜索树逻辑实现即可,搜索效率为 O(logN)

Node* Find(const K& key) {
    Node* cur = _root;
    while (cur) {
        if (cur->_kv.first < key) {
            cur = cur->_right;
        } else if(cur->_kv.first > key) {
            cur = cur->_left;
        } else {
            return cur;
        }
    }
    return nullptr;
}

2.5 红黑树的验证

这里获取最长路径和最短路径,检查最长路径不超过最短路径的 2 倍是不可行的,因为就算满足这个条件,红黑树也可能颜色不满足规则,当前暂时没出问题,后续继续插入还是会出问题的。所以我们还是去检查 4 点规则,满足这 4 点规则,一定能保证最长路径不超过最短路径的 2 倍。

  1. 规则 1 枚举颜色类型,天然实现保证了颜色不是黑色就是红色。
  2. 规则 2 直接检查根即可
  3. 规则 3 前序遍历检查,遇到红色结点查孩子不太方便,因为孩子有两个,且不一定存在,反过来检查父亲的颜色就方便多了。
  4. 规则 4 前序遍历,遍历过程中用形参记录跟到当前结点的 blackNum(黑色结点数量),前序遍历遇到黑色结点就++blackNum,走到空就计算出了一条路径的黑色结点数量。再任意一条路径黑色结点数量作为参考值,依次比较即可。

文章配图

// blackNum 根到当前结点的黑色结点的数量
bool Check(Node* root, int blackNum, const int refNum) {
    if (root == nullptr) {
        // 前序遍历走到空时,意味着一条路径走完了
        //cout << blackNum << endl;
        if (refNum != blackNum) {
            cout << "存在黑色结点的数量不相等的路径" << endl;
            return false;
        }
        return true;
    }
    // 检查孩子不太方便,因为孩子有两个,且不一定存在,反过来检查父亲就方便多了
    if (root->_col == RED && root->_parent->_col == RED) {
        cout << root->_kv.first << "存在连续的红色结点" << endl;
        return false;
    }
    if (root->_col == BLACK) {
        blackNum++;
    }
    return Check(root->_left, blackNum, refNum) && Check(root->_right, blackNum, refNum);
}

bool IsBalance() {
    if (_root == nullptr) return true;
    if (_root->_col == RED) return false; //参考值
    int refNum = 0;
    Node* cur = _root;
    while (cur) {
        if (cur->_col == BLACK) {
            ++refNum;
        }
        cur = cur->_left;
    }
    return Check(_root, 0, refNum);
}

2.6 红黑树的删除

红黑树的删除本章节不做讲解,有兴趣的同学可参考:《算法导论》或者《STL 源码剖析》中讲解。

三、完整代码

可以进行红黑树和 AVL 树的一些性能测试

RBTree.h

#pragma once
enum Colour { RED, BLACK };
// 这里我们默认按 key/value 结构实现
template<class K, class V>
struct RBTreeNode {
    // 这里更新控制平衡也要加入 parent 指针
    pair<K, V> _kv;
    RBTreeNode<K, V>* _left;
    RBTreeNode<K, V>* _right;
    RBTreeNode<K, V>* _parent;
    Colour _col;
    RBTreeNode(const pair<K, V>& kv) :_kv(kv) , _left(nullptr) , _right(nullptr) , _parent(nullptr) { }
};
template<class K,class V>
class RBTree {
    typedef RBTreeNode<K, V> Node;
public:
    bool Insert(const pair<K, V>& kv) {
        if (_root == nullptr) {
            _root = new Node(kv);
            _root->_col = BLACK;
            return true;
        }
        Node* parent = nullptr;
        Node* cur = _root;
        while (cur) {
            if (cur->_kv.first < kv.first) {
                parent = cur;
                cur = cur->_right;
            } else if (cur->_kv.first > kv.first) {
                parent = cur;
                cur = cur->_left;
            } else {
                return false;
            }
        }
        cur = new Node(kv);
        cur->_col = RED;
        if (parent->_kv.first < kv.first) {
            parent->_right = cur;
        } else {
            parent->_left = cur;
        }
        cur->_parent = parent;
        while (parent && parent->_col == RED) {
            Node* grandfather = parent->_parent;
            if (grandfather->_left == parent) {
                // g
                // p u
                Node* uncle = grandfather->_right;
                // 情况一:uncle 存在且为红
                if (uncle && uncle->_col == RED) {
                    // 变色
                    parent->_col = uncle->_col = BLACK;
                    grandfather->_col = RED;
                    // 继续往上处理
                    cur = grandfather;
                    parent = cur->_parent;
                } else // 情况二:uncle 不存在,或者存在且为黑
                {
                    if (cur == parent->_left) {
                        // 旋转 + 变色
                        // g
                        // p u
                        //c
                        RotateR(grandfather);
                        parent->_col = BLACK;
                        grandfather->_col = RED;
                    } else {
                        // 旋转 + 变色
                        // g
                        // p u
                        // c
                        RotateL(parent);
                        RotateR(grandfather);
                        cur->_col = BLACK;
                        grandfather->_col = RED;
                    }
                    break;
                }
            } else {
                // g
                // u p
                Node* uncle = grandfather->_left;
                // 情况一:叔叔存在且为红,变色即可
                if (uncle && uncle->_col == RED) {
                    parent->_col = uncle->_col = BLACK;
                    grandfather->_col = RED;
                    // 继续往上处理
                    cur = grandfather;
                    parent = cur->_parent;
                } else // 叔叔不存在,或者存在且为黑
                {
                    // 情况二:叔叔不存在或者存在且为黑
                    // 单旋 + 变色
                    // g
                    // u p
                    // c
                    if (cur == parent->_right) {
                        RotateL(grandfather);
                        parent->_col = BLACK;
                        grandfather->_col = RED;
                    } else {
                        //双旋 + 变色
                        // g
                        // u p
                        // c
                        RotateR(parent);
                        RotateL(grandfather);
                        cur->_col = BLACK;
                        grandfather->_col = RED;
                    }
                    break;
                }
            }
        }
        _root->_col = BLACK;
        return true;
    }
    void InOrder() {
        _InOrder(_root);
        cout << endl;
    }
    // blackNum 根到当前结点的黑色结点的数量
    bool Check(Node* root, int blackNum, const int refNum) {
        if (root == nullptr) {
            // 前序遍历走到空时,意味着一条路径走完了
            //cout << blackNum << endl;
            if (refNum != blackNum) {
                cout << "存在黑色结点的数量不相等的路径" << endl;
                return false;
            }
            return true;
        }
        // 检查孩子不太方便,因为孩子有两个,且不一定存在,反过来检查父亲就方便多了
        if (root->_col == RED && root->_parent->_col == RED) {
            cout << root->_kv.first << "存在连续的红色结点" << endl;
            return false;
        }
        if (root->_col == BLACK) {
            blackNum++;
        }
        return Check(root->_left, blackNum, refNum) && Check(root->_right, blackNum, refNum);
    }
    bool IsBalance() {
        if (_root == nullptr) return true;
        if (_root->_col == RED) return false;
        // 参考值
        int refNum = 0;
        Node* cur = _root;
        while (cur) {
            if (cur->_col == BLACK) {
                ++refNum;
            }
            cur = cur->_left;
        }
        return Check(_root, 0, refNum);
    }
    int Height() {
        return _Height(_root);
    }
    int Size() {
        return _Size(_root);
    }
    Node* Find(const K& key) {
        Node* cur = _root;
        while (cur) {
            if (cur->_kv.first < key) {
                cur = cur->_right;
            } else if (cur->_kv.first > key) {
                cur = cur->_left;
            } else {
                return cur;
            }
        }
        return nullptr;
    }
protected:
    int _Size(Node* root) {
        if (root == nullptr) return 0;
        return _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 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 (ppNode == nullptr)
        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* parentParent = parent->_parent;
        subR->_left = parent;
        parent->_parent = subR;
        if (parentParent == nullptr) {
            _root = subR;
            subR->_parent = nullptr;
        } else {
            if (parent == parentParent->_left) {
                parentParent->_left = subR;
            } else {
                parentParent->_right = subR;
            }
            subR->_parent = parentParent;
        }
    }
    void _InOrder(Node* root) {
        if (root == nullptr) {
            return;
        }
        _InOrder(root->_left);
        cout << root->_kv.first << ":" << root->_kv.second << endl;
        _InOrder(root->_right);
    }
private:
    Node* _root = nullptr;
};

AVLTree.h

#pragma once
template<class K, class V>
struct AVLTreeNode {
    // 需要 parent 指针,后续更新平衡因子可以看到
    pair<K, V> _kv;
    AVLTreeNode<K, V>* _left;
    AVLTreeNode<K, V>* _right;
    AVLTreeNode<K, V>* _parent;
    int _bf; // balance factor
    AVLTreeNode(const pair<K, V>& kv) :_kv(kv) , _left(nullptr) , _right(nullptr) , _parent(nullptr) , _bf(0) { }
};
template<class K, class V>
class AVLTree {
    typedef AVLTreeNode<K, V> Node;
public:
    bool Insert(const pair<K, V>& kv) {
        if (_root == nullptr) {
            _root = new Node(kv);
            return true;
        }
        Node* parent = nullptr;
        Node* cur = _root;
        while (cur) {
            if (cur->_kv.first < kv.first) {
                parent = cur;
                cur = cur->_right;
            } else if (cur->_kv.first > kv.first) {
                parent = cur;
                cur = cur->_left;
            } else {
                return false;
            }
        }
        cur = new Node(kv);
        if (parent->_kv.first < kv.first) {
            parent->_right = cur;
        } else {
            parent->_left = cur;
        }
        cur->_parent = parent;
        // 更新平衡因子
        while (parent) {
            if (cur == parent->_right) {
                parent->_bf++;
            } else {
                parent->_bf--;
            }
            if (parent->_bf == 0) {
                break;
            } else if (parent->_bf == 1 || parent->_bf == -1) {
                cur = parent;
                parent = parent->_parent;
            } else if (parent->_bf == 2 || parent->_bf == -2) {
                // 旋转
                if (parent->_bf == -2 && cur->_bf == -1) {
                    RotateR(parent);
                } else if (parent->_bf == 2 && cur->_bf == 1) {
                    RotateL(parent);
                } else if (parent->_bf == -2 && cur->_bf == 1) {
                    RotateLR(parent);
                } else if (parent->_bf == 2 && cur->_bf == -1) {
                    RotateRL(parent);
                } else {
                    assert(false);
                }
                break;
            } else {
                assert(false);
            }
        }
        return true;
    }
    void InOrder() {
        _InOrder(_root);
        cout << endl;
    }
    bool IsBalanceTree() {
        return _IsBalanceTree(_root);
    }
    Node* Find(const K& key) {
        Node* cur = _root;
        while (cur) {
            if (cur->_kv.first < key) {
                cur = cur->_right;
            } else if (cur->_kv.first > key) {
                cur = cur->_left;
            } else {
                return cur;
            }
        }
        return nullptr;
    }
    int Height() {
        return _Height(_root);
    }
    int Size() {
        return _Size(_root);
    }
private:
    int _Size(Node* root) {
        if (root == nullptr) return 0;
        return _Size(root->_left) + _Size(root->_right) + 1;
    }
    bool _IsBalanceTree(Node* root) {
        // 空树也是 AVL 树
        if (nullptr == root) return true;
        // 计算 pRoot 结点的平衡因子:即 pRoot 左右子树的高度差
        int leftHeight = _Height(root->_left);
        int rightHeight = _Height(root->_right);
        int diff = rightHeight - leftHeight;
        // 如果计算出的平衡因子与 pRoot 的平衡因子不相等,或者
        // pRoot 平衡因子的绝对值超过 1,则一定不是 AVL 树
        if (abs(diff) >= 2) {
            cout << root->_kv.first << "高度差异常" << endl;
            return false;
        }
        if (root->_bf != diff) {
            cout << root->_kv.first << "平衡因子异常" << endl;
            return false;
        }
        // pRoot 的左和右如果都是 AVL 树,则该树一定是 AVL 树
        return _IsBalanceTree(root->_left) && _IsBalanceTree(root->_right);
    }
    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 << ":" << root->_kv.second << endl;
        _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 (ppNode == nullptr)
        if (parent == _root) {
            _root = subL;
            subL->_parent = nullptr;
        } else {
            if (ppNode->_left == parent) {
                ppNode->_left = subL;
            } else {
                ppNode->_right = subL;
            }
            subL->_parent = ppNode;
        }
        parent->_bf = 0;
        subL->_bf = 0;
    }
    void RotateL(Node* parent) {
        Node* subR = parent->_right;
        Node* subRL = subR->_left;
        parent->_right = subRL;
        if (subRL) subRL->_parent = parent;
        Node* parentParent = parent->_parent;
        subR->_left = parent;
        parent->_parent = subR;
        if (parentParent == nullptr) {
            _root = subR;
            subR->_parent = nullptr;
        } else {
            if (parent == parentParent->_left) {
                parentParent->_left = subR;
            } else {
                parentParent->_right = subR;
            }
            subR->_parent = parentParent;
        }
        parent->_bf = subR->_bf = 0;
    }
    void RotateLR(Node* parent) {
        Node* subL = parent->_left;
        Node* subLR = subL->_right;
        int bf = subLR->_bf;
        RotateL(parent->_left);
        RotateR(parent);
        if (bf == -1) {
            subL->_bf = 0;
            parent->_bf = 1;
            subLR->_bf = 0;
        } else if (bf == 1) {
            subL->_bf = -1;
            parent->_bf = 0;
            subLR->_bf = 0;
        } else if (bf == 0) {
            subL->_bf = 0;
            parent->_bf = 0;
            subLR->_bf = 0;
        } else {
            assert(false);
        }
    }
    void RotateRL(Node* parent) {
        Node* subR = parent->_right;
        Node* subRL = subR->_left;
        int bf = subRL->_bf;
        RotateR(parent->_right);
        RotateL(parent);
        if (bf == 0) {
            subR->_bf = 0;
            subRL->_bf = 0;
            parent->_bf = 0;
        } else if (bf == 1) {
            subR->_bf = 0;
            subRL->_bf = 0;
            parent->_bf = -1;
        } else if (bf == -1) {
            subR->_bf = 1;
            subRL->_bf = 0;
            parent->_bf = 0;
        } else {
            assert(false);
        }
    }
private:
    Node* _root = nullptr;
};

test.cpp

#define _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
#include<vector>
#include<assert.h>
using namespace std;
#include"RBTree.h"
#include"AVLTree.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 };
    for (auto e : a) {
        /*if (e == 14) { int x = 0; }*/
        t.Insert({ e, e });
        cout << "Insert:" << e << "->";
        cout << t.IsBalance() << endl;
    }
    t.InOrder();
    cout << t.IsBalance() << 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 << t.IsBalance() << endl;
    cout << "RBTree Insert:" << end2 - begin2 << endl;
    cout << "RBTree Height:" << t.Height() << endl;
    cout << "RBTree 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 << "RBTree Find:" << end1 - begin1 << endl << endl;
}

void TestAVLTree2() {
    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();
    AVLTree<int, int> t;
    for (auto e : v) {
        t.Insert(make_pair(e, e));
    }
    size_t end2 = clock();
    cout << t.IsBalanceTree() << endl;
    cout << "AVLTree Insert:" << end2 - begin2 << endl;
    cout << "AVLTree Height:" << t.Height() << endl;
    cout << "AVLTree 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 << "AVLTree Find:" << end1 - begin1 << endl;
}

int main() {
    TestRBTree2();
    TestAVLTree2();
    return 0;
}

目录

  1. 一、红黑树的概念
  2. 1.1 红黑树的规则
  3. 1.2 思考一下,红黑树如何确保最长路径不超过最短路径的 2 倍的?
  4. 1.3 红黑树的效率
  5. 二、红黑树的实现
  6. 2.1 红黑树的结构
  7. 2.2 红黑树的插入
  8. 【红黑树树插入一个值的大概过程】
  9. 【情况 1:变色】
  10. 【情况 2:单旋 + 变色】
  11. 【情况 2:双旋 + 变色】
  12. 2.3 红黑树的插入代码实现
  13. 2.4 红黑树的查找
  14. 2.5 红黑树的验证
  15. 2.6 红黑树的删除
  16. 三、完整代码
  17. RBTree.h
  18. AVLTree.h
  19. test.cpp
  • 💰 8折买阿里云服务器限时8折了解详情
  • Magick API 一键接入全球大模型注册送1000万token查看
  • 🤖 一键搭建Deepseek满血版了解详情
  • 一键打造专属AI 智能体了解详情
极客日志微信公众号二维码

微信扫一扫,关注极客日志

微信公众号「极客日志V2」,在微信中扫描左侧二维码关注。展示文案:极客日志V2 zeeklog

更多推荐文章

查看全部
  • P1604 B 进制星球:C++ 高精度加法实现
  • 程序员如何接私活及兼职平台与技能路径解析
  • 英特尔 A770 显卡 AI 绘画环境搭建指南
  • Java 链表数据结构与 LinkedList 详解
  • 深入解析 Redisson 分布式锁核心原理与源码实现
  • MySQL 数据类型详解与选型指南
  • AIGC Bar API 接入与工程化实践指南
  • 深入理解 Kafka:核心架构、特性与运维实践
  • 应届生无项目经验,求职碰壁该如何应对?
  • 线性动态规划经典例题解析
  • Python 结合代理 IP 自动化采集音乐数据实战
  • DeerFlow 2.0:字节开源的超级 Agent 框架
  • AVL 树原理与 C++ 实现:构建自平衡二叉搜索树
  • 量化、算子融合与内存映射:C 语言实现边缘 AI 推理实战
  • Vue 自定义指令详解
  • 基础算法:滑动窗口(Python 实现)
  • CentOS 7 忘记 root 密码的重置方法
  • JVM 运行时数据区域详解:从内存结构到面试考点
  • Linux 文件存储结构原理:从 dentry 到 inode 再到硬链接
  • LangChain 调用国产大模型实战:以智谱 AI 为例

相关免费在线工具

  • 加密/解密文本

    使用加密算法(如AES、TripleDES、Rabbit或RC4)加密和解密文本明文。 在线工具,加密/解密文本在线工具,online

  • Gemini 图片去水印

    基于开源反向 Alpha 混合算法去除 Gemini/Nano Banana 图片水印,支持批量处理与下载。 在线工具,Gemini 图片去水印在线工具,online

  • Base64 字符串编码/解码

    将字符串编码和解码为其 Base64 格式表示形式即可。 在线工具,Base64 字符串编码/解码在线工具,online

  • Base64 文件转换器

    将字符串、文件或图像转换为其 Base64 表示形式。 在线工具,Base64 文件转换器在线工具,online

  • Markdown转HTML

    将 Markdown(GFM)转为 HTML 片段,浏览器内 marked 解析;与 HTML转Markdown 互为补充。 在线工具,Markdown转HTML在线工具,online

  • HTML转Markdown

    将 HTML 片段转为 GitHub Flavored Markdown,支持标题、列表、链接、代码块与表格等;浏览器内处理,可链接预填。 在线工具,HTML转Markdown在线工具,online