• 红黑树(4万字文章超详细,只为一个目的)


    我写这篇文章的主要目的其次才是积累知识,主要是因为我想打一个同学的脸.

    事情是这样的.我现在中学嘛,我们班上有一个同学他学了红黑树啊,就一副"不可一世"的样子.在我面前炫耀啊.当时我就想立马打他的脸,可是我有没有实力,所以才学习红黑树学到深夜,写了篇博客.言归正传,我们现在开始.

    红黑树是一种自平衡的二叉搜索树。每个节点额外存储了一个 color 字段 ("RED" or "BLACK"),用于确保树在插入和删除时保持平衡。

    性质

    一棵合法的红黑树必须遵循以下四条性质:

    1. 节点为红色或黑色
    2. NIL 节点(空叶子节点)为黑色
    3. 红色节点的子节点为黑色
    4. 从根节点到 NIL 节点的每条路径上的黑色节点数量相同

    注:部分资料中还加入了第五条性质,即根节点必须为黑色,这条性质要求完成插入操作后若根节点为红色则将其染黑,但由于将根节点染黑的操作也可以延迟至删除操作时进行,因此,该条性质并非必须满足。

    结构

    红黑树类的定义

    1. template <typename Key, typename Value, typename Compare = std::less>
    2. class RBTreeMap {
    3. // 排序函数
    4. Compare compare = Compare();
    5. // 节点结构体
    6. struct Node {
    7. ...
    8. };
    9. // 根节点指针
    10. Node* root = nullptr;
    11. // 记录红黑树中当前的节点个数
    12. size_t count = 0;
    13. }

    节点维护的信息

    IdentifierTypeDescription
    leftNode*左子节点指针
    rightNode*右子节点指针
    parentNode*父节点指针
    colorenum { BLACK, RED }颜色枚举
    keyKey节点键值,具有唯一性和可排序性
    valueValue节点内储存的值

    注:由于本文提供的代码示例中使用 std::share_ptr 进行内存管理,对此不熟悉的读者可以将下文中所有的 NodePtr 和 ConstNodePtr 理解为裸指针 Node*。但在实现删除操作时若使用 Node* 作为节点引用需注意应手动释放内存以避免内存泄漏,该操作在使用 std::shared_ptr 作为节点引用的示例代码中并未体现。

    过程

    注:由于红黑树是由 B 树衍生而来(发明时的最初的名字 symmetric binary B-tree 足以证明这点),并非直接由平衡二叉树外加限制条件推导而来,插入操作的后续维护和删除操作的后续维护中部分对操作的解释作用仅是帮助理解,并不能将其作为该操作的原理推导和证明。

    旋转操作

    旋转操作是多数平衡树能够维持平衡的关键,它能在不改变一棵合法 BST 中序遍历结果的情况下改变局部节点的深度。

    如上图,从左图到右图的过程被称为左旋,左旋操作会使得  \alpha子树上结点的深度均减 1,使  \beta子树上结点的深度均加 1,而  \delta子树上节点的深度则不变。从右图到左图的过程被称为右旋,右旋是左旋的镜像操作。

    这里给出红黑树中节点的左旋操作的示例代码:

    1. void rotateLeft(ConstNodePtr node) {
    2. // clang-format off
    3. // | |
    4. // N S
    5. // / \ l-rotate(N) / \
    6. // L S ==========> N R
    7. // / \ / \
    8. // M R L M
    9. assert(node != nullptr && node->right != nullptr);
    10. // clang-format on
    11. NodePtr parent = node->parent;
    12. Direction direction = node->direction();
    13. NodePtr successor = node->right;
    14. node->right = successor->left;
    15. successor->left = node;
    16. // 以下的操作用于维护各个节点的`parent`指针
    17. // `Direction`的定义以及`maintainRelationship`
    18. // 的实现请参照文章末尾的完整示例代码
    19. maintainRelationship(node);
    20. maintainRelationship(successor);
    21. switch (direction) {
    22. case Direction::ROOT:
    23. this->root = successor;
    24. break;
    25. case Direction::LEFT:
    26. parent->left = successor;
    27. break;
    28. case Direction::RIGHT:
    29. parent->right = successor;
    30. break;
    31. }
    32. successor->parent = parent;
    33. }

    注:代码中的 successor 并非平衡树中的后继节点,而是表示取代原本节点的新节点,由于在图示中 replacement 的简称 R 会与右子节点的简称 R 冲突,因此此处使用 successor 避免歧义。

    插入操作

    红黑树的插入操作与普通的 BST 类似,对于红黑树来说,新插入的节点初始为红色,完成插入后需根据插入节点及相关节点的状态进行修正以满足上文提到的四条性质。

    插入后的平衡维护

    Case 1

    该树原先为空,插入第一个节点后不需要进行修正。

    Case 2

    当前的节点的父节点为黑色且为根节点,这时性质已经满足,不需要进行修正。

    Case 3

    当前节点 N 的父节点 P 是为根节点且为红色,将其染为黑色即可,此时性质也已满足,不需要进一步修正。

    1. // clang-format off
    2. // Case 3: Parent is root and is RED
    3. // Paint parent to BLACK.
    4. //

      [P]

    5. // | ====> |
    6. //
    7. // p.s.
    8. // `` is a RED node;
    9. // `[X]` is a BLACK node (or NIL);
    10. // `{X}` is either a RED node or a BLACK node;
    11. // clang-format on
    12. assert(node->parent->isRed());
    13. node->parent->color = Node::BLACK;
    14. return;

    Case 4

    当前节点 N 的父节点 P 和叔节点 U 均为红色,此时 P 包含了一个红色子节点,违反了红黑树的性质,需要进行重新染色。由于在当前节点 N 之前该树是一棵合法的红黑树,根据性质 4 可以确定 N 的祖父节点 G 一定是黑色,这时只要后续操作可以保证以 G 为根节点的子树在不违反性质 4 的情况下再递归维护祖父节点 G 以保证性质 3 即可。

    因此,这种情况的维护需要:

    1. 将 P,U 节点染黑,将 G 节点染红(可以保证每条路径上黑色节点个数不发生改变)。
    2. 递归维护 G 节点(因为不确定 G 的父节点的状态,递归维护可以确保性质 3 成立)。
    1. // clang-format off
    2. // Case 4: Both parent and uncle are RED
    3. // Paint parent and uncle to BLACK;
    4. // Paint grandparent to RED.
    5. // [G]
    6. // / \ / \
    7. //

      ====> [P] [U]

    8. // / /
    9. //
    10. // clang-format on
    11. assert(node->parent->isRed());
    12. node->parent->color = Node::BLACK;
    13. node->uncle()->color = Node::BLACK;
    14. node->grandParent()->color = Node::RED;
    15. maintainAfterInsert(node->grandParent());
    16. return;

    Case 5

    当前节点 N 与父节点 P 的方向相反(即 N 节点为右子节点且父节点为左子节点,或 N 节点为左子节点且父节点为右子节点。类似 AVL 树中 LR 和 RL 的情况)。根据性质 4,若 N 为新插入节点,U 则为 NIL 黑色节点,否则为普通黑色节点。

    该种情况无法直接进行维护,需要通过旋转操作将子树结构调整为 Case 6 的初始状态并进入 Case 6 进行后续维护。

    1. // clang-format off
    2. // Case 5: Current node is the opposite direction as parent
    3. // Step 1. If node is a LEFT child, perform l-rotate to parent;
    4. // If node is a RIGHT child, perform r-rotate to parent.
    5. // Step 2. Goto Case 6.
    6. // [G] [G]
    7. // / \ rotate(P) / \
    8. //

      [U] ========> [U]

    9. // \ /
    10. //

    11. // clang-format on
    12. // Step 1: Rotation
    13. NodePtr parent = node->parent;
    14. if (node->direction() == Direction::LEFT) {
    15. rotateRight(node->parent);
    16. } else /* node->direction() == Direction::RIGHT */ {
    17. rotateLeft(node->parent);
    18. }
    19. node = parent;
    20. // Step 2: vvv

    Case 6

    当前节点 N 与父节点 P 的方向相同(即 N 节点为右子节点且父节点为右子节点,或 N 节点为左子节点且父节点为右子节点。类似 AVL 树中 LL 和 RR 的情况)。根据性质 4,若 N 为新插入节点,U 则为 NIL 黑色节点,否则为普通黑色节点。

    在这种情况下,若想在不改变结构的情况下使得子树满足性质 3,则需将 G 染成红色,将 P 染成黑色。但若这样维护的话则性质 4 被打破,且无法保证在 G 节点的父节点上性质 3 是否成立。而选择通过旋转改变子树结构后再进行重新染色即可同时满足性质 3 和 4。

    因此,这种情况的维护需要:

    1. 若 N 为左子节点则左旋祖父节点 G,否则右旋祖父节点 G.(该操作使得旋转过后 P - N 这条路径上的黑色节点个数比 P - G - U 这条路径上少 1,暂时打破性质 4)。
    2. 重新染色,将 P 染黑,将 N 染红,同时满足了性质 3 和 4。
      1. // clang-format off
      2. // Case 6: Current node is the same direction as parent
      3. // Step 1. If node is a LEFT child, perform r-rotate to grandparent;
      4. // If node is a RIGHT child, perform l-rotate to grandparent.
      5. // Step 2. Paint parent (before rotate) to BLACK;
      6. // Paint grandparent (before rotate) to RED.
      7. // [G]

        [P]

      8. // / \ rotate(G) / \ repaint / \
      9. //

        [U] ========> [G] ======>

      10. // / \ \
      11. // [U] [U]
      12. // clang-format on
      13. assert(node->grandParent() != nullptr);
      14. // Step 1
      15. if (node->parent->direction() == Direction::LEFT) {
      16. rotateRight(node->grandParent());
      17. } else {
      18. rotateLeft(node->grandParent());
      19. }
      20. // Step 2
      21. node->parent->color = Node::BLACK;
      22. node->sibling()->color = Node::RED;
      23. return;

      删除操作

      红黑树的删除操作情况繁多,较为复杂。这部分内容主要通过代码示例来进行讲解。大多数红黑树的实现选择将节点的删除以及删除之后的维护写在同一个函数或逻辑块中(例如 Wikipedia 给出的 代码示例linux 内核中的 rbtree 以及 GNU libstdc++ 中的 std::_Rb_tree 都使用了类似的写法)。笔者则认为这种实现方式并不利于对算法本身的理解,因此,本文给出的示例代码参考了 OpenJDK 中 TreeMap 的实现,将删除操作本身与删除后的平衡维护操作解耦成两个独立的函数,并对这两部分的逻辑单独进行分析。

      Case 0

      若待删除节点为根节点的话,直接删除即可,这里不将其算作删除操作的 3 种基本情况中。

      Case 1

      若待删除节点 N 既有左子节点又有右子节点,则需找到它的前驱或后继节点进行替换(仅替换数据,不改变节点颜色和内部引用关系),则后续操作中只需要将后继节点删除即可。这部分操作与普通 BST 完全相同,在此不再过多赘述。

      注:这里选择的前驱或后继节点保证不会是一个既有非 NIL 左子节点又有非 NIL 右子节点的节点。这里拿后继节点进行简单说明:若该节点包含非空左子节点,则该节点并非是 N 节点右子树上键值最小的节点,与后继节点的性质矛盾,因此后继节点的左子节点必须为 NIL。

    1. // clang-format off
    2. // Case 1: If the node is strictly internal
    3. // Step 1. Find the successor S with the smallest key
    4. // and its parent P on the right subtree.
    5. // Step 2. Swap the data (key and value) of S and N,
    6. // S is the node that will be deleted in place of N.
    7. // Step 3. N = S, goto Case 2, 3
    8. // | |
    9. // N S
    10. // / \ / \
    11. // L .. swap(N, S) L ..
    12. // | =========> |
    13. // P P
    14. // / \ / \
    15. // S .. N ..
    16. // clang-format on
    17. // Step 1
    18. NodePtr successor = node->right;
    19. NodePtr parent = node;
    20. while (successor->left != nullptr) {
    21. parent = successor;
    22. successor = parent->left;
    23. }
    24. // Step 2
    25. swapNode(node, successor);
    26. maintainRelationship(parent);
    27. // Step 3: vvv

    Case 2

    待删除节点为叶子节点,若该节点为红色,直接删除即可,删除后仍能保证红黑树的 4 条性质。若为黑色,删除后性质 4 被打破,需要重新进行维护。

    注:由于维护操作不会改变待删除节点的任何结构和数据,因此此处的代码示例中为了实现方便起见选择先进行维护,再解引用相关节点。

    1. // clang-format off
    2. // Case 2: Current node is a leaf
    3. // Step 1. Unlink and remove it.
    4. // Step 2. If N is BLACK, maintain N;
    5. // If N is RED, do nothing.
    6. // clang-format on
    7. // The maintain operation won't change the node itself,
    8. // so we can perform maintain operation before unlink the node.
    9. if (node->isBlack()) {
    10. maintainAfterRemove(node);
    11. }
    12. if (node->direction() == Direction::LEFT) {
    13. node->parent->left = nullptr;
    14. } else /* node->direction() == Direction::RIGHT */ {
    15. node->parent->right = nullptr;
    16. }

    Case 3

    待删除节点有且仅有一个非 NIL 子节点,若待删除节点为红色,直接使用其子节点 S 替换即可;若为黑色,则直接使用子节点 S 替代会打破性质 4,需要在使用 S 替代后判断 S 的颜色,若为红色,则将其染黑后即可满足性质 4,否则需要进行维护才可以满足性质 4。

    1. // Case 3: Current node has a single left or right child
    2. // Step 1. Replace N with its child
    3. // Step 2. If N is BLACK, maintain N
    4. NodePtr parent = node->parent;
    5. NodePtr replacement = (node->left != nullptr ? node->left : node->right);
    6. switch (node->direction()) {
    7. case Direction::ROOT:
    8. this->root = replacement;
    9. break;
    10. case Direction::LEFT:
    11. parent->left = replacement;
    12. break;
    13. case Direction::RIGHT:
    14. parent->right = replacement;
    15. break;
    16. }
    17. if (!node->isRoot()) {
    18. replacement->parent = parent;
    19. }
    20. if (node->isBlack()) {
    21. if (replacement->isRed()) {
    22. replacement->color = Node::BLACK;
    23. } else {
    24. maintainAfterRemove(replacement);
    25. }
    26. }

    删除后的平衡维护

    Case 1

    兄弟节点 (sibling node) S 为红色,则父节点 P 和侄节点 (nephew node) C 和 D 必为黑色(否则违反性质 3)。与插入后维护操作的 Case 5 类似,这种情况下无法通过直接的旋转或染色操作使其满足所有性质,因此通过前置操作优先保证部分结构满足性质,再进行后续维护即可。

    这种情况的维护需要:

    1. 若待删除节点 N 为左子节点,左旋 P; 若为右子节点,右旋 P。
    2. 将 S 染黑,P 染红(保证 S 节点的父节点满足性质 4)。
    3. 此时只需根据结构对以当前 P 节点为根的子树进行维护即可(无需再考虑旋转染色后的 S 和 D 节点)。
    1. // clang-format off
    2. // Case 1: Sibling is RED, parent and nephews must be BLACK
    3. // Step 1. If N is a left child, left rotate P;
    4. // If N is a right child, right rotate P.
    5. // Step 2. Paint S to BLACK, P to RED
    6. // Step 3. Goto Case 2, 3, 4, 5
    7. // [P] [S]
    8. // / \ l-rotate(P) / \ repaint / \
    9. // [N] ==========> [P] [D] ======>

      [D]

    10. // / \ / \ / \
    11. // [C] [D] [N] [C] [N] [C]
    12. // clang-format on
    13. ConstNodePtr parent = node->parent;
    14. assert(parent != nullptr && parent->isBlack());
    15. assert(sibling->left != nullptr && sibling->left->isBlack());
    16. assert(sibling->right != nullptr && sibling->right->isBlack());
    17. // Step 1
    18. rotateSameDirection(node->parent, direction);
    19. // Step 2
    20. sibling->color = Node::BLACK;
    21. parent->color = Node::RED;
    22. // Update sibling after rotation
    23. sibling = node->sibling();
    24. // Step 3: vvv

    Case 2

    兄弟节点 S 和侄节点 C, D 均为黑色,父节点 P 为红色。此时只需将 S 染黑,将 P 染红即可满足性质 3 和 4。

    1. // clang-format off
    2. // Case 2: Sibling and nephews are BLACK, parent is RED
    3. // Swap the color of P and S
    4. //

      [P]

    5. // / \ / \
    6. // [N] [S] ====> [N]
    7. // / \ / \
    8. // [C] [D] [C] [D]
    9. // clang-format on
    10. sibling->color = Node::RED;
    11. node->parent->color = Node::BLACK;
    12. return;

    Case 3

    兄弟节点 S,父节点 P 以及侄节点 C, D 均为黑色。

    此时也无法通过一步操作同时满足性质 3 和 4,因此选择将 S 染红,优先满足局部性质 4 的成立,再递归维护 P 节点根据上部结构进行后续维护。

    1. // clang-format off
    2. // Case 3: Sibling, parent and nephews are all black
    3. // Step 1. Paint S to RED
    4. // Step 2. Recursively maintain P
    5. // [P] [P]
    6. // / \ / \
    7. // [N] [S] ====> [N]
    8. // / \ / \
    9. // [C] [D] [C] [D]
    10. // clang-format on
    11. sibling->color = Node::RED;
    12. maintainAfterRemove(node->parent);
    13. return;

    Case 4

    兄弟节点是黑色,且与 N 同向的侄节点 C(由于没有固定中文翻译,下文还是统一将其称作 close nephew) 为红色,与 N 反向的侄节点 D(同理,下文称作 distant nephew) 为黑色,父节点既可为红色又可为黑色。

    此时同样无法通过一步操作使其满足性质,因此优先选择将其转变为 Case 5 的状态利用后续 Case 5 的维护过程进行修正。

    该过程分为三步:

    1. 若 N 为左子节点,右旋 P,否则左旋 P。
    2. 将节点 C 染红,将节点 S 染黑。
    3. 此时已满足 Case 5 的条件,进入 Case 5 完成后续维护。

    1. // clang-format off
    2. // Case 4: Sibling is BLACK, close nephew is RED,
    3. // distant nephew is BLACK
    4. // Step 1. If N is a left child, right rotate P;
    5. // If N is a right child, left rotate P.
    6. // Step 2. Swap the color of close nephew and sibling
    7. // Step 3. Goto case 5
    8. // {P} {P}
    9. // {P} / \ / \
    10. // / \ r-rotate(S) [N] repaint [N] [C]
    11. // [N] [S] ==========> \ ======> \
    12. // / \ [S]
    13. // [D] \ \
    14. // [D] [D]
    15. // clang-format on
    16. // Step 1
    17. rotateOppositeDirection(sibling, direction);
    18. // Step 2
    19. closeNephew->color = Node::BLACK;
    20. sibling->color = Node::RED;
    21. // Update sibling and nephews after rotation
    22. sibling = node->sibling();
    23. closeNephew = direction == Direction::LEFT ? sibling->left : sibling->right;
    24. distantNephew = direction == Direction::LEFT ? sibling->right : sibling->left;
    25. // Step 3: vvv

    Case 5

    兄弟节点是黑色,且 close nephew 节点 C 为红色,distant nephew 节点 D 为黑色,父节点既可为红色又可为黑色。此时性质 4 无法满足,通过旋转操作使得黑色节点 S 变为该子树的根节点再进行染色即可满足性质 4。具体步骤如下:

    1. 若 N 为左子节点,左旋 P,反之右旋 P。
    2. 交换父节点 P 和兄弟节点 S 的颜色,此时性质 3 可能被打破。
    3. 将 distant nephew 节点 D 染黑,同时保证了性质 3 和 4。
    1. // clang-format off
    2. // Case 5: Sibling is BLACK, close nephew is BLACK,
    3. // distant nephew is RED
    4. // Step 1. If N is a left child, left rotate P;
    5. // If N is a right child, right rotate P.
    6. // Step 2. Swap the color of parent and sibling.
    7. // Step 3. Paint distant nephew D to BLACK.
    8. // {P} [S] {S}
    9. // / \ l-rotate(P) / \ repaint / \
    10. // [N] [S] ==========> {P} ======> [P] [D]
    11. // / \ / \ / \
    12. // [C] [N] [C] [N] [C]
    13. // clang-format on
    14. assert(closeNephew == nullptr || closeNephew->isBlack());
    15. assert(distantNephew->isRed());
    16. // Step 1
    17. rotateSameDirection(node->parent, direction);
    18. // Step 2
    19. sibling->color = node->parent->color;
    20. node->parent->color = Node::BLACK;
    21. // Step 3
    22. distantNephew->color = Node::BLACK;
    23. return;

    红黑树与 4 阶 B 树 (2-3-4 树)的关系

    红黑树是由德国计算机科学家 Rudolf Bayer 在 1972 年从 B 树上改进过来的,红黑树在当时被称作 "symmetric binary B-tree",因此与 B 树有众多相似之处。比如红黑树与 4 阶 B 树每个簇(对于红黑树来说一个簇是一个非 NIL 黑色节点和它的两个子节点,对 B 树来说一个簇就是一个节点)的最大容量为 3 且最小填充量均为 。因此我们甚至可以说红黑树与 4 阶 B 树 (2-3-4 树)在结构上是等价的。

    对这方面内容感兴趣的可以观看 从 2-3-4 树的角度学习理解红黑树(视频) 进行学习。

    虽然二者在结构上是等价的,但这并不意味这二者可以互相取代或者在所有情况下都可以互换使用。最显然的例子就是数据库的索引,由于 B 树不存在旋转操作,因此其所有节点的存储位置都是可以被确定的,这种结构对于不区分堆栈的磁盘来说显然比红黑树动态分配节点存储空间要更加合适。另外一点就是由于 B 树/B+ 树内储存的数据都是连续的,对于有着大量连续查询需求的数据库来说更加友好。而对于小数据量随机插入/查询的需求,由于 B 树的每个节点都存储了若干条记录,因此发生 cache miss 时就需要将整个节点的所有数据读入缓存中,在这些情况下 BST(红黑树,AVL,Splay 等)则反而会优与 B 树/B+ 树。对这方面内容感兴趣的读者可以去阅读一下 为什么 rust 中的 Map 使用的是 B 树而不是像其他主流语言一样使用红黑树

    红黑树在实际工程项目中的使用

    由于红黑树是目前主流工业界综合效率最高的内存型平衡树,其在实际的工程项目中有着广泛的使用,这里列举几个实际的使用案例并给出相应的源码链接,以便读者进行对比学习。

    Linux

    源码:

    Linux 中的红黑树所有操作均使用循环迭代进行实现,保证效率的同时又增加了大量的注释来保证代码可读性,十分建议读者阅读学习。Linux 内核中的红黑树使用非常广泛,这里仅列举几个经典案例。

    CFS 非实时任务调度

    Linux 的稳定内核版本在 2.6.24 之后,使用了新的调度程序 CFS,所有非实时可运行进程都以虚拟运行时间为键值用一棵红黑树进行维护,以完成更公平高效地调度所有任务。CFS 弃用 active/expired 数组和动态计算优先级,不再跟踪任务的睡眠时间和区别是否交互任务,而是在调度中采用基于时间计算键值的红黑树来选取下一个任务,根据所有任务占用 CPU 时间的状态来确定调度任务优先级。

    epoll

    epoll 全称 event poll,是 Linux 内核实现 IO 多路复用 (IO multiplexing) 的一个实现,是原先 poll/select 的改进版。Linux 中 epoll 的实现选择使用红黑树来储存文件描述符。

    Nginx

    源码:

    nginx 中的用户态定时器是通过红黑树实现的。在 nginx 中,所有 timer 节点都由一棵红黑树进行维护,在 worker 进程的每一次循环中都会调用 ngx_process_events_and_timers 函数,在该函数中就会调用处理定时器的函数 ngx_event_expire_timers,每次该函数都不断的从红黑树中取出时间值最小的,查看他们是否已经超时,然后执行他们的函数,直到取出的节点的时间没有超时为止。

    关于 nginx 中红黑树的源码分析公开资源很多,读者可以自行查找学习。

    STL

    源码:

    大多数 STL 中的 std::map 和 std::set 的内部数据结构就是一棵红黑树(例如上面提到的这些)。不过值得注意的是,这些红黑树(包括可能有读者用过的 std::_Rb_tree) 都不是 C++ 标准,虽然部分竞赛(例如 NOIP) 并未命令禁止这类数据结构,但还是应当注意这类标准库中的非标准实现不应该在工程项目中直接使用。

    由于 STL 的特殊性,其中大多数实现的代码可读性都不高,因此并不建议读者使用 STL 学习红黑树。

    OpenJDK

    源码:

    JDK 中的 TreeMap 和 TreeSet 都是使用红黑树作为底层数据结构的。同时在 JDK 1.8 之后 HashMap 内部哈希表中每个表项的链表长度超过 8 时也会自动转变为红黑树以提升查找效率。

    笔者认为,JDK 中的红黑树实现是主流红黑树实现中可读性最高的,本文提供的参考代码很大程度上借鉴了 JDK 中 TreeMap 的实现,因此也建议读者阅读学习 JDK 中 TreeMap 的实现。

    参考代码

    下面的代码是用红黑树实现的 Map,即有序不可重映射:

    1. /**
    2. * @file RBTreeMap.hpp
    3. * @brief An RBTree-based map implementation
    4. * @details The map is sorted according to the natural ordering of its
    5. * keys or by a {@code Compare} function provided; This implementation
    6. * provides guaranteed log(n) time cost for the contains, get, insert
    7. * and remove operations.
    8. * @author [r.ivance](https://github.com/RIvance)
    9. */
    10. #ifndef RBTREE_MAP_HPP
    11. #define RBTREE_MAP_HPP
    12. #include
    13. #include
    14. #include
    15. #include
    16. #include
    17. #include
    18. #include
    19. #include
    20. /**
    21. * An RBTree-based map implementation
    22. * https://en.wikipedia.org/wiki/Red–black_tree
    23. *
    24. * A red–black tree (RBTree) is a kind of self-balancing binary search tree.
    25. * Each node stores an extra field representing "color" (RED or BLACK), used
    26. * to ensure that the tree remains balanced during insertions and deletions.
    27. *
    28. * In addition to the requirements imposed on a binary search tree the following
    29. * must be satisfied by a red–black tree:
    30. *
    31. * 1. Every node is either RED or BLACK.
    32. * 2. All NIL nodes (`nullptr` in this implementation) are considered BLACK.
    33. * 3. A RED node does not have a RED child.
    34. * 4. Every path from a given node to any of its descendant NIL nodes goes
    35. * through the same number of BLACK nodes.
    36. *
    37. * @tparam Key the type of keys maintained by this map
    38. * @tparam Value the type of mapped values
    39. * @tparam Compare the compare function
    40. */
    41. template <typename Key, typename Value, typename Compare = std::less >
    42. class RBTreeMap {
    43. private:
    44. using USize = size_t;
    45. Compare compare = Compare();
    46. public:
    47. struct Entry {
    48. Key key;
    49. Value value;
    50. bool operator==(const Entry &rhs) const noexcept {
    51. return this->key == rhs.key && this->value == rhs.value;
    52. }
    53. bool operator!=(const Entry &rhs) const noexcept {
    54. return this->key != rhs.key || this->value != rhs.value;
    55. }
    56. };
    57. private:
    58. struct Node {
    59. using Ptr = std::shared_ptr;
    60. using Provider = const std::function<Ptr(void)> &;
    61. using Consumer = const std::function<void(const Ptr &)> &;
    62. enum { RED, BLACK } color = RED;
    63. enum Direction { LEFT = -1, ROOT = 0, RIGHT = 1 };
    64. Key key;
    65. Value value{};
    66. Ptr parent = nullptr;
    67. Ptr left = nullptr;
    68. Ptr right = nullptr;
    69. explicit Node(Key k) : key(std::move(k)) {}
    70. explicit Node(Key k, Value v) : key(std::move(k)), value(std::move(v)) {}
    71. ~Node() = default;
    72. inline bool isLeaf() const noexcept {
    73. return this->left == nullptr && this->right == nullptr;
    74. }
    75. inline bool isRoot() const noexcept { return this->parent == nullptr; }
    76. inline bool isRed() const noexcept { return this->color == RED; }
    77. inline bool isBlack() const noexcept { return this->color == BLACK; }
    78. inline Direction direction() const noexcept {
    79. if (this->parent != nullptr) {
    80. if (this == this->parent->left.get()) {
    81. return Direction::LEFT;
    82. } else {
    83. return Direction::RIGHT;
    84. }
    85. } else {
    86. return Direction::ROOT;
    87. }
    88. }
    89. inline Ptr &sibling() const noexcept {
    90. assert(!this->isRoot());
    91. if (this->direction() == LEFT) {
    92. return this->parent->right;
    93. } else {
    94. return this->parent->left;
    95. }
    96. }
    97. inline bool hasSibling() const noexcept {
    98. return !this->isRoot() && this->sibling() != nullptr;
    99. }
    100. inline Ptr &uncle() const noexcept {
    101. assert(this->parent != nullptr);
    102. return parent->sibling();
    103. }
    104. inline bool hasUncle() const noexcept {
    105. return !this->isRoot() && this->parent->hasSibling();
    106. }
    107. inline Ptr &grandParent() const noexcept {
    108. assert(this->parent != nullptr);
    109. return this->parent->parent;
    110. }
    111. inline bool hasGrandParent() const noexcept {
    112. return !this->isRoot() && this->parent->parent != nullptr;
    113. }
    114. inline void release() noexcept {
    115. // avoid memory leak caused by circular reference
    116. this->parent = nullptr;
    117. if (this->left != nullptr) {
    118. this->left->release();
    119. }
    120. if (this->right != nullptr) {
    121. this->right->release();
    122. }
    123. }
    124. inline Entry entry() const { return Entry{key, value}; }
    125. static Ptr from(const Key &k) { return std::make_shared(Node(k)); }
    126. static Ptr from(const Key &k, const Value &v) {
    127. return std::make_shared(Node(k, v));
    128. }
    129. };
    130. using NodePtr = typename Node::Ptr;
    131. using ConstNodePtr = const NodePtr &;
    132. using Direction = typename Node::Direction;
    133. using NodeProvider = typename Node::Provider;
    134. using NodeConsumer = typename Node::Consumer;
    135. NodePtr root = nullptr;
    136. USize count = 0;
    137. using K = const Key &;
    138. using V = const Value &;
    139. public:
    140. using EntryList = std::vector;
    141. using KeyValueConsumer = const std::function<void(K, V)> &;
    142. using MutKeyValueConsumer = const std::function<void(K, Value &)> &;
    143. using KeyValueFilter = const std::function<bool(K, V)> &;
    144. class NoSuchMappingException : protected std::exception {
    145. private:
    146. const char *message;
    147. public:
    148. explicit NoSuchMappingException(const char *msg) : message(msg) {}
    149. const char *what() const noexcept override { return message; }
    150. };
    151. RBTreeMap() noexcept = default;
    152. ~RBTreeMap() noexcept {
    153. // Unlinking circular references to avoid memory leak
    154. this->clear();
    155. }
    156. /**
    157. * Returns the number of entries in this map.
    158. * @return size_t
    159. */
    160. inline USize size() const noexcept { return this->count; }
    161. /**
    162. * Returns true if this collection contains no elements.
    163. * @return bool
    164. */
    165. inline bool empty() const noexcept { return this->count == 0; }
    166. /**
    167. * Removes all of the elements from this map.
    168. */
    169. void clear() noexcept {
    170. // Unlinking circular references to avoid memory leak
    171. if (this->root != nullptr) {
    172. this->root->release();
    173. this->root = nullptr;
    174. }
    175. this->count = 0;
    176. }
    177. /**
    178. * Returns the value to which the specified key is mapped; If this map
    179. * contains no mapping for the key, a {@code NoSuchMappingException} will
    180. * be thrown.
    181. * @param key
    182. * @return RBTreeMap::Value
    183. * @throws NoSuchMappingException
    184. */
    185. Value get(K key) const {
    186. if (this->root == nullptr) {
    187. throw NoSuchMappingException("Invalid key");
    188. } else {
    189. NodePtr node = this->getNode(this->root, key);
    190. if (node != nullptr) {
    191. return node->value;
    192. } else {
    193. throw NoSuchMappingException("Invalid key");
    194. }
    195. }
    196. }
    197. /**
    198. * Returns the value to which the specified key is mapped; If this map
    199. * contains no mapping for the key, a new mapping with a default value
    200. * will be inserted.
    201. * @param key
    202. * @return RBTreeMap::Value &
    203. */
    204. Value &getOrDefault(K key) {
    205. if (this->root == nullptr) {
    206. this->root = Node::from(key);
    207. this->root->color = Node::BLACK;
    208. this->count += 1;
    209. return this->root->value;
    210. } else {
    211. return this
    212. ->getNodeOrProvide(this->root, key,
    213. [&key]() { return Node::from(key); })
    214. ->value;
    215. }
    216. }
    217. /**
    218. * Returns true if this map contains a mapping for the specified key.
    219. * @param key
    220. * @return bool
    221. */
    222. bool contains(K key) const {
    223. return this->getNode(this->root, key) != nullptr;
    224. }
    225. /**
    226. * Associates the specified value with the specified key in this map.
    227. * @param key
    228. * @param value
    229. */
    230. void insert(K key, V value) {
    231. if (this->root == nullptr) {
    232. this->root = Node::from(key, value);
    233. this->root->color = Node::BLACK;
    234. this->count += 1;
    235. } else {
    236. this->insert(this->root, key, value);
    237. }
    238. }
    239. /**
    240. * If the specified key is not already associated with a value, associates
    241. * it with the given value and returns true, else returns false.
    242. * @param key
    243. * @param value
    244. * @return bool
    245. */
    246. bool insertIfAbsent(K key, V value) {
    247. USize sizeBeforeInsertion = this->size();
    248. if (this->root == nullptr) {
    249. this->root = Node::from(key, value);
    250. this->root->color = Node::BLACK;
    251. this->count += 1;
    252. } else {
    253. this->insert(this->root, key, value, false);
    254. }
    255. return this->size() > sizeBeforeInsertion;
    256. }
    257. /**
    258. * If the specified key is not already associated with a value, associates
    259. * it with the given value and returns the value, else returns the associated
    260. * value.
    261. * @param key
    262. * @param value
    263. * @return RBTreeMap::Value &
    264. */
    265. Value &getOrInsert(K key, V value) {
    266. if (this->root == nullptr) {
    267. this->root = Node::from(key, value);
    268. this->root->color = Node::BLACK;
    269. this->count += 1;
    270. return root->value;
    271. } else {
    272. NodePtr node = getNodeOrProvide(this->root, key,
    273. [&]() { return Node::from(key, value); });
    274. return node->value;
    275. }
    276. }
    277. Value operator[](K key) const { return this->get(key); }
    278. Value &operator[](K key) { return this->getOrDefault(key); }
    279. /**
    280. * Removes the mapping for a key from this map if it is present;
    281. * Returns true if the mapping is present else returns false
    282. * @param key the key of the mapping
    283. * @return bool
    284. */
    285. bool remove(K key) {
    286. if (this->root == nullptr) {
    287. return false;
    288. } else {
    289. return this->remove(this->root, key, [](ConstNodePtr) {});
    290. }
    291. }
    292. /**
    293. * Removes the mapping for a key from this map if it is present and returns
    294. * the value which is mapped to the key; If this map contains no mapping for
    295. * the key, a {@code NoSuchMappingException} will be thrown.
    296. * @param key
    297. * @return RBTreeMap::Value
    298. * @throws NoSuchMappingException
    299. */
    300. Value getAndRemove(K key) {
    301. Value result;
    302. NodeConsumer action = [&](ConstNodePtr node) { result = node->value; };
    303. if (root == nullptr) {
    304. throw NoSuchMappingException("Invalid key");
    305. } else {
    306. if (remove(this->root, key, action)) {
    307. return result;
    308. } else {
    309. throw NoSuchMappingException("Invalid key");
    310. }
    311. }
    312. }
    313. /**
    314. * Gets the entry corresponding to the specified key; if no such entry
    315. * exists, returns the entry for the least key greater than the specified
    316. * key; if no such entry exists (i.e., the greatest key in the Tree is less
    317. * than the specified key), a {@code NoSuchMappingException} will be thrown.
    318. * @param key
    319. * @return RBTreeMap::Entry
    320. * @throws NoSuchMappingException
    321. */
    322. Entry getCeilingEntry(K key) const {
    323. if (this->root == nullptr) {
    324. throw NoSuchMappingException("No ceiling entry in this map");
    325. }
    326. NodePtr node = this->root;
    327. while (node != nullptr) {
    328. if (key == node->key) {
    329. return node->entry();
    330. }
    331. if (compare(key, node->key)) {
    332. /* key < node->key */
    333. if (node->left != nullptr) {
    334. node = node->left;
    335. } else {
    336. return node->entry();
    337. }
    338. } else {
    339. /* key > node->key */
    340. if (node->right != nullptr) {
    341. node = node->right;
    342. } else {
    343. while (node->direction() == Direction::RIGHT) {
    344. if (node != nullptr) {
    345. node = node->parent;
    346. } else {
    347. throw NoSuchMappingException(
    348. "No ceiling entry exists in this map");
    349. }
    350. }
    351. if (node->parent == nullptr) {
    352. throw NoSuchMappingException("No ceiling entry exists in this map");
    353. }
    354. return node->parent->entry();
    355. }
    356. }
    357. }
    358. throw NoSuchMappingException("No ceiling entry in this map");
    359. }
    360. /**
    361. * Gets the entry corresponding to the specified key; if no such entry exists,
    362. * returns the entry for the greatest key less than the specified key;
    363. * if no such entry exists, a {@code NoSuchMappingException} will be thrown.
    364. * @param key
    365. * @return RBTreeMap::Entry
    366. * @throws NoSuchMappingException
    367. */
    368. Entry getFloorEntry(K key) const {
    369. if (this->root == nullptr) {
    370. throw NoSuchMappingException("No floor entry exists in this map");
    371. }
    372. NodePtr node = this->root;
    373. while (node != nullptr) {
    374. if (key == node->key) {
    375. return node->entry();
    376. }
    377. if (compare(key, node->key)) {
    378. /* key < node->key */
    379. if (node->left != nullptr) {
    380. node = node->left;
    381. } else {
    382. while (node->direction() == Direction::LEFT) {
    383. if (node != nullptr) {
    384. node = node->parent;
    385. } else {
    386. throw NoSuchMappingException("No floor entry exists in this map");
    387. }
    388. }
    389. if (node->parent == nullptr) {
    390. throw NoSuchMappingException("No floor entry exists in this map");
    391. }
    392. return node->parent->entry();
    393. }
    394. } else {
    395. /* key > node->key */
    396. if (node->right != nullptr) {
    397. node = node->right;
    398. } else {
    399. return node->entry();
    400. }
    401. }
    402. }
    403. throw NoSuchMappingException("No floor entry exists in this map");
    404. }
    405. /**
    406. * Gets the entry for the least key greater than the specified
    407. * key; if no such entry exists, returns the entry for the least
    408. * key greater than the specified key; if no such entry exists,
    409. * a {@code NoSuchMappingException} will be thrown.
    410. * @param key
    411. * @return RBTreeMap::Entry
    412. * @throws NoSuchMappingException
    413. */
    414. Entry getHigherEntry(K key) {
    415. if (this->root == nullptr) {
    416. throw NoSuchMappingException("No higher entry exists in this map");
    417. }
    418. NodePtr node = this->root;
    419. while (node != nullptr) {
    420. if (compare(key, node->key)) {
    421. /* key < node->key */
    422. if (node->left != nullptr) {
    423. node = node->left;
    424. } else {
    425. return node->entry();
    426. }
    427. } else {
    428. /* key >= node->key */
    429. if (node->right != nullptr) {
    430. node = node->right;
    431. } else {
    432. while (node->direction() == Direction::RIGHT) {
    433. if (node != nullptr) {
    434. node = node->parent;
    435. } else {
    436. throw NoSuchMappingException(
    437. "No higher entry exists in this map");
    438. }
    439. }
    440. if (node->parent == nullptr) {
    441. throw NoSuchMappingException("No higher entry exists in this map");
    442. }
    443. return node->parent->entry();
    444. }
    445. }
    446. }
    447. throw NoSuchMappingException("No higher entry exists in this map");
    448. }
    449. /**
    450. * Returns the entry for the greatest key less than the specified key; if
    451. * no such entry exists (i.e., the least key in the Tree is greater than
    452. * the specified key), a {@code NoSuchMappingException} will be thrown.
    453. * @param key
    454. * @return RBTreeMap::Entry
    455. * @throws NoSuchMappingException
    456. */
    457. Entry getLowerEntry(K key) const {
    458. if (this->root == nullptr) {
    459. throw NoSuchMappingException("No lower entry exists in this map");
    460. }
    461. NodePtr node = this->root;
    462. while (node != nullptr) {
    463. if (compare(key, node->key) || key == node->key) {
    464. /* key <= node->key */
    465. if (node->left != nullptr) {
    466. node = node->left;
    467. } else {
    468. while (node->direction() == Direction::LEFT) {
    469. if (node != nullptr) {
    470. node = node->parent;
    471. } else {
    472. throw NoSuchMappingException("No lower entry exists in this map");
    473. }
    474. }
    475. if (node->parent == nullptr) {
    476. throw NoSuchMappingException("No lower entry exists in this map");
    477. }
    478. return node->parent->entry();
    479. }
    480. } else {
    481. /* key > node->key */
    482. if (node->right != nullptr) {
    483. node = node->right;
    484. } else {
    485. return node->entry();
    486. }
    487. }
    488. }
    489. throw NoSuchMappingException("No lower entry exists in this map");
    490. }
    491. /**
    492. * Remove all entries that satisfy the filter condition.
    493. * @param filter
    494. */
    495. void removeAll(KeyValueFilter filter) {
    496. std::vector keys;
    497. this->inorderTraversal([&](ConstNodePtr node) {
    498. if (filter(node->key, node->value)) {
    499. keys.push_back(node->key);
    500. }
    501. });
    502. for (const Key &key : keys) {
    503. this->remove(key);
    504. }
    505. }
    506. /**
    507. * Performs the given action for each key and value entry in this map.
    508. * The value is immutable for the action.
    509. * @param action
    510. */
    511. void forEach(KeyValueConsumer action) const {
    512. this->inorderTraversal(
    513. [&](ConstNodePtr node) { action(node->key, node->value); });
    514. }
    515. /**
    516. * Performs the given action for each key and value entry in this map.
    517. * The value is mutable for the action.
    518. * @param action
    519. */
    520. void forEachMut(MutKeyValueConsumer action) {
    521. this->inorderTraversal(
    522. [&](ConstNodePtr node) { action(node->key, node->value); });
    523. }
    524. /**
    525. * Returns a list containing all of the entries in this map.
    526. * @return RBTreeMap::EntryList
    527. */
    528. EntryList toEntryList() const {
    529. EntryList entryList;
    530. this->inorderTraversal(
    531. [&](ConstNodePtr node) { entryList.push_back(node->entry()); });
    532. return entryList;
    533. }
    534. private:
    535. static void maintainRelationship(ConstNodePtr node) {
    536. if (node->left != nullptr) {
    537. node->left->parent = node;
    538. }
    539. if (node->right != nullptr) {
    540. node->right->parent = node;
    541. }
    542. }
    543. static void swapNode(NodePtr &lhs, NodePtr &rhs) {
    544. std::swap(lhs->key, rhs->key);
    545. std::swap(lhs->value, rhs->value);
    546. std::swap(lhs, rhs);
    547. }
    548. void rotateLeft(ConstNodePtr node) {
    549. // clang-format off
    550. // | |
    551. // N S
    552. // / \ l-rotate(N) / \
    553. // L S ==========> N R
    554. // / \ / \
    555. // M R L M
    556. assert(node != nullptr && node->right != nullptr);
    557. // clang-format on
    558. NodePtr parent = node->parent;
    559. Direction direction = node->direction();
    560. NodePtr successor = node->right;
    561. node->right = successor->left;
    562. successor->left = node;
    563. maintainRelationship(node);
    564. maintainRelationship(successor);
    565. switch (direction) {
    566. case Direction::ROOT:
    567. this->root = successor;
    568. break;
    569. case Direction::LEFT:
    570. parent->left = successor;
    571. break;
    572. case Direction::RIGHT:
    573. parent->right = successor;
    574. break;
    575. }
    576. successor->parent = parent;
    577. }
    578. void rotateRight(ConstNodePtr node) {
    579. // clang-format off
    580. // | |
    581. // N S
    582. // / \ r-rotate(N) / \
    583. // S R ==========> L N
    584. // / \ / \
    585. // L M M R
    586. assert(node != nullptr && node->left != nullptr);
    587. // clang-format on
    588. NodePtr parent = node->parent;
    589. Direction direction = node->direction();
    590. NodePtr successor = node->left;
    591. node->left = successor->right;
    592. successor->right = node;
    593. maintainRelationship(node);
    594. maintainRelationship(successor);
    595. switch (direction) {
    596. case Direction::ROOT:
    597. this->root = successor;
    598. break;
    599. case Direction::LEFT:
    600. parent->left = successor;
    601. break;
    602. case Direction::RIGHT:
    603. parent->right = successor;
    604. break;
    605. }
    606. successor->parent = parent;
    607. }
    608. inline void rotateSameDirection(ConstNodePtr node, Direction direction) {
    609. assert(direction != Direction::ROOT);
    610. if (direction == Direction::LEFT) {
    611. rotateLeft(node);
    612. } else {
    613. rotateRight(node);
    614. }
    615. }
    616. inline void rotateOppositeDirection(ConstNodePtr node, Direction direction) {
    617. assert(direction != Direction::ROOT);
    618. if (direction == Direction::LEFT) {
    619. rotateRight(node);
    620. } else {
    621. rotateLeft(node);
    622. }
    623. }
    624. void maintainAfterInsert(NodePtr node) {
    625. assert(node != nullptr);
    626. if (node->isRoot()) {
    627. // Case 1: Current node is root (RED)
    628. // No need to fix.
    629. assert(node->isRed());
    630. return;
    631. }
    632. if (node->parent->isBlack()) {
    633. // Case 2: Parent is BLACK
    634. // No need to fix.
    635. return;
    636. }
    637. if (node->parent->isRoot()) {
    638. // clang-format off
    639. // Case 3: Parent is root and is RED
    640. // Paint parent to BLACK.
    641. //

      [P]

    642. // | ====> |
    643. //
    644. // p.s.
    645. // `` is a RED node;
    646. // `[X]` is a BLACK node (or NIL);
    647. // `{X}` is either a RED node or a BLACK node;
    648. // clang-format on
    649. assert(node->parent->isRed());
    650. node->parent->color = Node::BLACK;
    651. return;
    652. }
    653. if (node->hasUncle() && node->uncle()->isRed()) {
    654. // clang-format off
    655. // Case 4: Both parent and uncle are RED
    656. // Paint parent and uncle to BLACK;
    657. // Paint grandparent to RED.
    658. // [G]
    659. // / \ / \
    660. //

      ====> [P] [U]

    661. // / /
    662. //
    663. // clang-format on
    664. assert(node->parent->isRed());
    665. node->parent->color = Node::BLACK;
    666. node->uncle()->color = Node::BLACK;
    667. node->grandParent()->color = Node::RED;
    668. maintainAfterInsert(node->grandParent());
    669. return;
    670. }
    671. if (!node->hasUncle() || node->uncle()->isBlack()) {
    672. // Case 5 & 6: Parent is RED and Uncle is BLACK
    673. // p.s. NIL nodes are also considered BLACK
    674. assert(!node->isRoot());
    675. if (node->direction() != node->parent->direction()) {
    676. // clang-format off
    677. // Case 5: Current node is the opposite direction as parent
    678. // Step 1. If node is a LEFT child, perform l-rotate to parent;
    679. // If node is a RIGHT child, perform r-rotate to parent.
    680. // Step 2. Goto Case 6.
    681. // [G] [G]
    682. // / \ rotate(P) / \
    683. //

      [U] ========> [U]

    684. // \ /
    685. //

    686. // clang-format on
    687. // Step 1: Rotation
    688. NodePtr parent = node->parent;
    689. if (node->direction() == Direction::LEFT) {
    690. rotateRight(node->parent);
    691. } else /* node->direction() == Direction::RIGHT */ {
    692. rotateLeft(node->parent);
    693. }
    694. node = parent;
    695. // Step 2: vvv
    696. }
    697. // clang-format off
    698. // Case 6: Current node is the same direction as parent
    699. // Step 1. If node is a LEFT child, perform r-rotate to grandparent;
    700. // If node is a RIGHT child, perform l-rotate to grandparent.
    701. // Step 2. Paint parent (before rotate) to BLACK;
    702. // Paint grandparent (before rotate) to RED.
    703. // [G]

      [P]

    704. // / \ rotate(G) / \ repaint / \
    705. //

      [U] ========> [G] ======>

    706. // / \ \
    707. // [U] [U]
    708. // clang-format on
    709. assert(node->grandParent() != nullptr);
    710. // Step 1
    711. if (node->parent->direction() == Direction::LEFT) {
    712. rotateRight(node->grandParent());
    713. } else {
    714. rotateLeft(node->grandParent());
    715. }
    716. // Step 2
    717. node->parent->color = Node::BLACK;
    718. node->sibling()->color = Node::RED;
    719. return;
    720. }
    721. }
    722. NodePtr getNodeOrProvide(NodePtr &node, K key, NodeProvider provide) {
    723. assert(node != nullptr);
    724. if (key == node->key) {
    725. return node;
    726. }
    727. assert(key != node->key);
    728. NodePtr result;
    729. if (compare(key, node->key)) {
    730. /* key < node->key */
    731. if (node->left == nullptr) {
    732. result = node->left = provide();
    733. node->left->parent = node;
    734. maintainAfterInsert(node->left);
    735. this->count += 1;
    736. } else {
    737. result = getNodeOrProvide(node->left, key, provide);
    738. }
    739. } else {
    740. /* key > node->key */
    741. if (node->right == nullptr) {
    742. result = node->right = provide();
    743. node->right->parent = node;
    744. maintainAfterInsert(node->right);
    745. this->count += 1;
    746. } else {
    747. result = getNodeOrProvide(node->right, key, provide);
    748. }
    749. }
    750. return result;
    751. }
    752. NodePtr getNode(ConstNodePtr node, K key) const {
    753. assert(node != nullptr);
    754. if (key == node->key) {
    755. return node;
    756. }
    757. if (compare(key, node->key)) {
    758. /* key < node->key */
    759. return node->left == nullptr ? nullptr : getNode(node->left, key);
    760. } else {
    761. /* key > node->key */
    762. return node->right == nullptr ? nullptr : getNode(node->right, key);
    763. }
    764. }
    765. void insert(NodePtr &node, K key, V value, bool replace = true) {
    766. assert(node != nullptr);
    767. if (key == node->key) {
    768. if (replace) {
    769. node->value = value;
    770. }
    771. return;
    772. }
    773. assert(key != node->key);
    774. if (compare(key, node->key)) {
    775. /* key < node->key */
    776. if (node->left == nullptr) {
    777. node->left = Node::from(key, value);
    778. node->left->parent = node;
    779. maintainAfterInsert(node->left);
    780. this->count += 1;
    781. } else {
    782. insert(node->left, key, value, replace);
    783. }
    784. } else {
    785. /* key > node->key */
    786. if (node->right == nullptr) {
    787. node->right = Node::from(key, value);
    788. node->right->parent = node;
    789. maintainAfterInsert(node->right);
    790. this->count += 1;
    791. } else {
    792. insert(node->right, key, value, replace);
    793. }
    794. }
    795. }
    796. void maintainAfterRemove(ConstNodePtr node) {
    797. if (node->isRoot()) {
    798. return;
    799. }
    800. assert(node->isBlack() && node->hasSibling());
    801. Direction direction = node->direction();
    802. NodePtr sibling = node->sibling();
    803. if (sibling->isRed()) {
    804. // clang-format off
    805. // Case 1: Sibling is RED, parent and nephews must be BLACK
    806. // Step 1. If N is a left child, left rotate P;
    807. // If N is a right child, right rotate P.
    808. // Step 2. Paint S to BLACK, P to RED
    809. // Step 3. Goto Case 2, 3, 4, 5
    810. // [P] [S]
    811. // / \ l-rotate(P) / \ repaint / \
    812. // [N] ==========> [P] [D] ======>

      [D]

    813. // / \ / \ / \
    814. // [C] [D] [N] [C] [N] [C]
    815. // clang-format on
    816. ConstNodePtr parent = node->parent;
    817. assert(parent != nullptr && parent->isBlack());
    818. assert(sibling->left != nullptr && sibling->left->isBlack());
    819. assert(sibling->right != nullptr && sibling->right->isBlack());
    820. // Step 1
    821. rotateSameDirection(node->parent, direction);
    822. // Step 2
    823. sibling->color = Node::BLACK;
    824. parent->color = Node::RED;
    825. // Update sibling after rotation
    826. sibling = node->sibling();
    827. // Step 3: vvv
    828. }
    829. NodePtr closeNephew =
    830. direction == Direction::LEFT ? sibling->left : sibling->right;
    831. NodePtr distantNephew =
    832. direction == Direction::LEFT ? sibling->right : sibling->left;
    833. bool closeNephewIsBlack = closeNephew == nullptr || closeNephew->isBlack();
    834. bool distantNephewIsBlack =
    835. distantNephew == nullptr || distantNephew->isBlack();
    836. assert(sibling->isBlack());
    837. if (closeNephewIsBlack && distantNephewIsBlack) {
    838. if (node->parent->isRed()) {
    839. // clang-format off
    840. // Case 2: Sibling and nephews are BLACK, parent is RED
    841. // Swap the color of P and S
    842. //

      [P]

    843. // / \ / \
    844. // [N] [S] ====> [N]
    845. // / \ / \
    846. // [C] [D] [C] [D]
    847. // clang-format on
    848. sibling->color = Node::RED;
    849. node->parent->color = Node::BLACK;
    850. return;
    851. } else {
    852. // clang-format off
    853. // Case 3: Sibling, parent and nephews are all black
    854. // Step 1. Paint S to RED
    855. // Step 2. Recursively maintain P
    856. // [P] [P]
    857. // / \ / \
    858. // [N] [S] ====> [N]
    859. // / \ / \
    860. // [C] [D] [C] [D]
    861. // clang-format on
    862. sibling->color = Node::RED;
    863. maintainAfterRemove(node->parent);
    864. return;
    865. }
    866. } else {
    867. if (closeNephew != nullptr && closeNephew->isRed()) {
    868. // clang-format off
    869. // Case 4: Sibling is BLACK, close nephew is RED,
    870. // distant nephew is BLACK
    871. // Step 1. If N is a left child, right rotate P;
    872. // If N is a right child, left rotate P.
    873. // Step 2. Swap the color of close nephew and sibling
    874. // Step 3. Goto case 5
    875. // {P} {P}
    876. // {P} / \ / \
    877. // / \ r-rotate(S) [N] repaint [N] [C]
    878. // [N] [S] ==========> \ ======> \
    879. // / \ [S]
    880. // [D] \ \
    881. // [D] [D]
    882. // clang-format on
    883. // Step 1
    884. rotateOppositeDirection(sibling, direction);
    885. // Step 2
    886. closeNephew->color = Node::BLACK;
    887. sibling->color = Node::RED;
    888. // Update sibling and nephews after rotation
    889. sibling = node->sibling();
    890. closeNephew =
    891. direction == Direction::LEFT ? sibling->left : sibling->right;
    892. distantNephew =
    893. direction == Direction::LEFT ? sibling->right : sibling->left;
    894. // Step 3: vvv
    895. }
    896. // clang-format off
    897. // Case 5: Sibling is BLACK, close nephew is BLACK,
    898. // distant nephew is RED
    899. // {P} [S]
    900. // / \ l-rotate(P) / \
    901. // [N] [S] ==========> {P}
    902. // / \ / \
    903. // [C] [N] [C]
    904. // clang-format on
    905. assert(closeNephew == nullptr || closeNephew->isBlack());
    906. assert(distantNephew->isRed());
    907. // Step 1
    908. rotateSameDirection(node->parent, direction);
    909. // Step 2
    910. sibling->color = node->parent->color;
    911. node->parent->color = Node::BLACK;
    912. if (distantNephew != nullptr) {
    913. distantNephew->color = Node::BLACK;
    914. }
    915. return;
    916. }
    917. }
    918. bool remove(NodePtr node, K key, NodeConsumer action) {
    919. assert(node != nullptr);
    920. if (key != node->key) {
    921. if (compare(key, node->key)) {
    922. /* key < node->key */
    923. NodePtr &left = node->left;
    924. if (left != nullptr && remove(left, key, action)) {
    925. maintainRelationship(node);
    926. return true;
    927. } else {
    928. return false;
    929. }
    930. } else {
    931. /* key > node->key */
    932. NodePtr &right = node->right;
    933. if (right != nullptr && remove(right, key, action)) {
    934. maintainRelationship(node);
    935. return true;
    936. } else {
    937. return false;
    938. }
    939. }
    940. }
    941. assert(key == node->key);
    942. action(node);
    943. if (this->size() == 1) {
    944. // Current node is the only node of the tree
    945. this->clear();
    946. return true;
    947. }
    948. if (node->left != nullptr && node->right != nullptr) {
    949. // clang-format off
    950. // Case 1: If the node is strictly internal
    951. // Step 1. Find the successor S with the smallest key
    952. // and its parent P on the right subtree.
    953. // Step 2. Swap the data (key and value) of S and N,
    954. // S is the node that will be deleted in place of N.
    955. // Step 3. N = S, goto Case 2, 3
    956. // | |
    957. // N S
    958. // / \ / \
    959. // L .. swap(N, S) L ..
    960. // | =========> |
    961. // P P
    962. // / \ / \
    963. // S .. N ..
    964. // clang-format on
    965. // Step 1
    966. NodePtr successor = node->right;
    967. NodePtr parent = node;
    968. while (successor->left != nullptr) {
    969. parent = successor;
    970. successor = parent->left;
    971. }
    972. // Step 2
    973. swapNode(node, successor);
    974. maintainRelationship(parent);
    975. // Step 3: vvv
    976. }
    977. if (node->isLeaf()) {
    978. // Current node must not be the root
    979. assert(node->parent != nullptr);
    980. // Case 2: Current node is a leaf
    981. // Step 1. Unlink and remove it.
    982. // Step 2. If N is BLACK, maintain N;
    983. // If N is RED, do nothing.
    984. // The maintain operation won't change the node itself,
    985. // so we can perform maintain operation before unlink the node.
    986. if (node->isBlack()) {
    987. maintainAfterRemove(node);
    988. }
    989. if (node->direction() == Direction::LEFT) {
    990. node->parent->left = nullptr;
    991. } else /* node->direction() == Direction::RIGHT */ {
    992. node->parent->right = nullptr;
    993. }
    994. } else /* !node->isLeaf() */ {
    995. assert(node->left == nullptr || node->right == nullptr);
    996. // Case 3: Current node has a single left or right child
    997. // Step 1. Replace N with its child
    998. // Step 2. If N is BLACK, maintain N
    999. NodePtr parent = node->parent;
    1000. NodePtr replacement = (node->left != nullptr ? node->left : node->right);
    1001. switch (node->direction()) {
    1002. case Direction::ROOT:
    1003. this->root = replacement;
    1004. break;
    1005. case Direction::LEFT:
    1006. parent->left = replacement;
    1007. break;
    1008. case Direction::RIGHT:
    1009. parent->right = replacement;
    1010. break;
    1011. }
    1012. if (!node->isRoot()) {
    1013. replacement->parent = parent;
    1014. }
    1015. if (node->isBlack()) {
    1016. if (replacement->isRed()) {
    1017. replacement->color = Node::BLACK;
    1018. } else {
    1019. maintainAfterRemove(replacement);
    1020. }
    1021. }
    1022. }
    1023. this->count -= 1;
    1024. return true;
    1025. }
    1026. void inorderTraversal(NodeConsumer action) const {
    1027. if (this->root == nullptr) {
    1028. return;
    1029. }
    1030. std::stack stack;
    1031. NodePtr node = this->root;
    1032. while (node != nullptr || !stack.empty()) {
    1033. while (node != nullptr) {
    1034. stack.push(node);
    1035. node = node->left;
    1036. }
    1037. if (!stack.empty()) {
    1038. node = stack.top();
    1039. stack.pop();
    1040. action(node);
    1041. node = node->right;
    1042. }
    1043. }
    1044. }
    1045. };
    1046. #endif // RBTREE_MAP_HPP

    打了一个晚上终于打出来的(虽然最后一段die码是复制的).

    可是我发现了一个问题,我是先画好的图它忽然今天就传不上去了,这是我很奇怪的,请各位大佬指教一下

  • 相关阅读:
    app如何新增广告位以提升广告变现收益?
    Docker
    (多级缓存)多级缓存
    Redis如何实现多可用区?
    微服务系列之网关(二) konga配置操作
    Docker连接Mysql
    一条通往服务器所有端口的隧道
    QImage相关
    k8s + docker 基于 kubeadm 多节点集群部署
    【重识云原生】第四章云网络4.8.3.1节——Open vSwitch简介
  • 原文地址:https://blog.csdn.net/cyyyyds857/article/details/127813774