Some authors, e.g. Cormen & al.,1claim "the root is black" as fifth requirement; but not Mehlhorn & Sanders2or Sedgewick & Wayne.3Since the root can always be changed from red to black, this rule has little effect on analysis. This article also omits it, because it slightly disturbs the recursive algorithms and proofs.
voidrotateLeft(ConstNodePtrnode){// clang-format off// | |// N S// / \ l-rotate(N) / \ // L S ==========> N R// / \ / \ // M R L Massert(node!=nullptr&&node->right!=nullptr);// clang-format onNodePtrparent=node->parent;Directiondirection=node->direction();NodePtrsuccessor=node->right;node->right=successor->left;successor->left=node;// 以下的操作用于维护各个节点的`parent`指针// `Direction`的定义以及`maintainRelationship`// 的实现请参照文章末尾的完整示例代码maintainRelationship(node);maintainRelationship(successor);switch(direction){caseDirection::ROOT:this->root=successor;break;caseDirection::LEFT:parent->left=successor;break;caseDirection::RIGHT:parent->right=successor;break;}successor->parent=parent;}
注:代码中的 successor 并非平衡树中的后继节点,而是表示取代原本节点的新节点,由于在图示中 replacement 的简称 R 会与右子节点的简称 R 冲突,因此此处使用 successor 避免歧义。
当前节点 N 的父节点 P 是为根节点且为红色,将其染为黑色即可,此时性质也已满足,不需要进一步修正。
实现
1 2 3 4 5 6 7 8 91011121314
// clang-format off// Case 3: Parent is root and is RED// Paint parent to BLACK.// <P> [P]// | ====> |// <N> <N>// p.s.// `<X>` is a RED node;// `[X]` is a BLACK node (or NIL);// `{X}` is either a RED node or a BLACK node;// clang-format onassert(node->parent->isRed());node->parent->color=Node::BLACK;return;
Case 4
当前节点 N 的父节点 P 和叔节点 U 均为红色,此时 P 包含了一个红色子节点,违反了红黑树的性质,需要进行重新染色。由于在当前节点 N 之前该树是一棵合法的红黑树,根据性质 4 可以确定 N 的祖父节点 G 一定是黑色,这时只要后续操作可以保证以 G 为根节点的子树在不违反性质 4 的情况下再递归维护祖父节点 G 以保证性质 3 即可。
因此,这种情况的维护需要:
将 P,U 节点染黑,将 G 节点染红(可以保证每条路径上黑色节点个数不发生改变)。
递归维护 G 节点(因为不确定 G 的父节点的状态,递归维护可以确保性质 3 成立)。
实现
1 2 3 4 5 6 7 8 910111213141516
// clang-format off// Case 4: Both parent and uncle are RED// Paint parent and uncle to BLACK;// Paint grandparent to RED.// [G] <G>// / \ / \// <P> <U> ====> [P] [U]// / /// <N> <N>// clang-format onassert(node->parent->isRed());node->parent->color=Node::BLACK;node->uncle()->color=Node::BLACK;node->grandParent()->color=Node::RED;maintainAfterInsert(node->grandParent());return;
Case 5
当前节点 N 与父节点 P 的方向相反(即 N 节点为右子节点且父节点为左子节点,或 N 节点为左子节点且父节点为右子节点。类似 AVL 树中 LR 和 RL 的情况)。根据性质 4,若 N 为新插入节点,U 则为 NIL 黑色节点,否则为普通黑色节点。
该种情况无法直接进行维护,需要通过旋转操作将子树结构调整为 Case 6 的初始状态并进入 Case 6 进行后续维护。
实现
1 2 3 4 5 6 7 8 9101112131415161718192021
// clang-format off// Case 5: Current node is the opposite direction as parent// Step 1. If node is a LEFT child, perform l-rotate to parent;// If node is a RIGHT child, perform r-rotate to parent.// Step 2. Goto Case 6.// [G] [G]// / \ rotate(P) / \// <P> [U] ========> <N> [U]// \ /// <N> <P>// clang-format on// Step 1: RotationNodePtrparent=node->parent;if(node->direction()==Direction::LEFT){rotateRight(node->parent);}else/* node->direction() == Direction::RIGHT */{rotateLeft(node->parent);}node=parent;// Step 2: vvv
Case 6
当前节点 N 与父节点 P 的方向相同(即 N 节点为右子节点且父节点为右子节点,或 N 节点为左子节点且父节点为右子节点。类似 AVL 树中 LL 和 RR 的情况)。根据性质 4,若 N 为新插入节点,U 则为 NIL 黑色节点,否则为普通黑色节点。
在这种情况下,若想在不改变结构的情况下使得子树满足性质 3,则需将 G 染成红色,将 P 染成黑色。但若这样维护的话则性质 4 被打破,且无法保证在 G 节点的父节点上性质 3 是否成立。而选择通过旋转改变子树结构后再进行重新染色即可同时满足性质 3 和 4。
因此,这种情况的维护需要:
若 N 为左子节点则左旋祖父节点 G,否则右旋祖父节点 G.(该操作使得旋转过后 P - N 这条路径上的黑色节点个数比 P - G - U 这条路径上少 1,暂时打破性质 4)。
// clang-format off// Case 6: Current node is the same direction as parent// Step 1. If node is a LEFT child, perform r-rotate to grandparent;// If node is a RIGHT child, perform l-rotate to grandparent.// Step 2. Paint parent (before rotate) to BLACK;// Paint grandparent (before rotate) to RED.// [G] <P> [P]// / \ rotate(G) / \ repaint / \// <P> [U] ========> <N> [G] ======> <N> <G>// / \ \// <N> [U] [U]// clang-format onassert(node->grandParent()!=nullptr);// Step 1if(node->parent->direction()==Direction::LEFT){rotateRight(node->grandParent());}else{rotateLeft(node->grandParent());}// Step 2node->parent->color=Node::BLACK;node->sibling()->color=Node::RED;return;
删除操作
红黑树的删除操作情况繁多,较为复杂。这部分内容主要通过代码示例来进行讲解。大多数红黑树的实现选择将节点的删除以及删除之后的维护写在同一个函数或逻辑块中(例如 Wikipedia 给出的 代码示例,linux 内核中的 rbtree 以及 GNU libstdc++ 中的 std::_Rb_tree 都使用了类似的写法)。笔者则认为这种实现方式并不利于对算法本身的理解,因此,本文给出的示例代码参考了 OpenJDK 中 TreeMap 的实现,将删除操作本身与删除后的平衡维护操作解耦成两个独立的函数,并对这两部分的逻辑单独进行分析。
Case 0
若待删除节点为根节点的话,直接删除即可,这里不将其算作删除操作的 3 种基本情况中。
Case 1
若待删除节点 N 既有左子节点又有右子节点,则需找到它的前驱或后继节点进行替换(仅替换数据,不改变节点颜色和内部引用关系),则后续操作中只需要将后继节点删除即可。这部分操作与普通 BST 完全相同,在此不再过多赘述。
注:这里选择的前驱或后继节点保证不会是一个既有非 NIL 左子节点又有非 NIL 右子节点的节点。这里拿后继节点进行简单说明:若该节点包含非空左子节点,则该节点并非是 N 节点右子树上键值最小的节点,与后继节点的性质矛盾,因此后继节点的左子节点必须为 NIL。
// clang-format off// Case 1: If the node is strictly internal// Step 1. Find the successor S with the smallest key// and its parent P on the right subtree.// Step 2. Swap the data (key and value) of S and N,// S is the node that will be deleted in place of N.// Step 3. N = S, goto Case 2, 3// | |// N S// / \ / \// L .. swap(N, S) L ..// | =========> |// P P// / \ / \// S .. N ..// clang-format on// Step 1NodePtrsuccessor=node->right;NodePtrparent=node;while(successor->left!=nullptr){parent=successor;successor=parent->left;}// Step 2swapNode(node,successor);maintainRelationship(parent);// Step 3: vvv
// clang-format off// Case 2: Current node is a leaf// Step 1. Unlink and remove it.// Step 2. If N is BLACK, maintain N;// If N is RED, do nothing.// clang-format on// The maintain operation won't change the node itself,// so we can perform maintain operation before unlink the node.if(node->isBlack()){maintainAfterRemove(node);}if(node->direction()==Direction::LEFT){node->parent->left=nullptr;}else/* node->direction() == Direction::RIGHT */{node->parent->right=nullptr;}
Case 3
待删除节点有且仅有一个非 NIL 子节点,若待删除节点为红色,直接使用其子节点 S 替换即可;若为黑色,则直接使用子节点 S 替代会打破性质 4,需要在使用 S 替代后判断 S 的颜色,若为红色,则将其染黑后即可满足性质 4,否则需要进行维护才可以满足性质 4。
// Case 3: Current node has a single left or right child// Step 1. Replace N with its child// Step 2. If N is BLACK, maintain NNodePtrparent=node->parent;NodePtrreplacement=(node->left!=nullptr?node->left:node->right);switch(node->direction()){caseDirection::ROOT:this->root=replacement;break;caseDirection::LEFT:parent->left=replacement;break;caseDirection::RIGHT:parent->right=replacement;break;}if(!node->isRoot()){replacement->parent=parent;}if(node->isBlack()){if(replacement->isRed()){replacement->color=Node::BLACK;}else{maintainAfterRemove(replacement);}}
删除后的平衡维护
Case 1
兄弟节点 (sibling node) S 为红色,则父节点 P 和侄节点 (nephew node) C 和 D 必为黑色(否则违反性质 3)。与插入后维护操作的 Case 5 类似,这种情况下无法通过直接的旋转或染色操作使其满足所有性质,因此通过前置操作优先保证部分结构满足性质,再进行后续维护即可。
这种情况的维护需要:
若待删除节点 N 为左子节点,左旋 P; 若为右子节点,右旋 P。
将 S 染黑,P 染红(保证 S 节点的父节点满足性质 4)。
此时只需根据结构对以当前 P 节点为根的子树进行维护即可(无需再考虑旋转染色后的 S 和 D 节点)。
实现
1 2 3 4 5 6 7 8 910111213141516171819202122232425
// clang-format off// Case 1: Sibling is RED, parent and nephews must be BLACK// Step 1. If N is a left child, left rotate P;// If N is a right child, right rotate P.// Step 2. Paint S to BLACK, P to RED// Step 3. Goto Case 2, 3, 4, 5// [P] <S> [S]// / \ l-rotate(P) / \ repaint / \// [N] <S> ==========> [P] [D] ======> <P> [D]// / \ / \ / \// [C] [D] [N] [C] [N] [C]// clang-format onConstNodePtrparent=node->parent;assert(parent!=nullptr&&parent->isBlack());assert(sibling->left!=nullptr&&sibling->left->isBlack());assert(sibling->right!=nullptr&&sibling->right->isBlack());// Step 1rotateSameDirection(node->parent,direction);// Step 2sibling->color=Node::BLACK;parent->color=Node::RED;// Update sibling after rotationsibling=node->sibling();// Step 3: vvv
Case 2
兄弟节点 S 和侄节点 C, D 均为黑色,父节点 P 为红色。此时只需将 S 染红,将 P 染黑即可满足性质 3 和 4。
实现
1 2 3 4 5 6 7 8 9101112
// clang-format off// Case 2: Sibling and nephews are BLACK, parent is RED// Swap the color of P and S// <P> [P]// / \ / \// [N] [S] ====> [N] <S>// / \ / \// [C] [D] [C] [D]// clang-format onsibling->color=Node::RED;node->parent->color=Node::BLACK;return;
Case 3
兄弟节点 S,父节点 P 以及侄节点 C, D 均为黑色。
此时也无法通过一步操作同时满足性质 3 和 4,因此选择将 S 染红,优先满足局部性质 4 的成立,再递归维护 P 节点根据上部结构进行后续维护。
实现
1 2 3 4 5 6 7 8 910111213
// clang-format off// Case 3: Sibling, parent and nephews are all black// Step 1. Paint S to RED// Step 2. Recursively maintain P// [P] [P]// / \ / \// [N] [S] ====> [N] <S>// / \ / \// [C] [D] [C] [D]// clang-format onsibling->color=Node::RED;maintainAfterRemove(node->parent);return;
Case 4
兄弟节点是黑色,且与 N 同向的侄节点 C(由于没有固定中文翻译,下文还是统一将其称作 close nephew)为红色,与 N 反向的侄节点 D(同理,下文称作 distant nephew)为黑色,父节点既可为红色又可为黑色。
此时同样无法通过一步操作使其满足性质,因此优先选择将其转变为 Case 5 的状态利用后续 Case 5 的维护过程进行修正。
// clang-format off// Case 4: Sibling is BLACK, close nephew is RED,// distant nephew is BLACK// Step 1. If N is a left child, right rotate P;// If N is a right child, left rotate P.// Step 2. Swap the color of close nephew and sibling// Step 3. Goto case 5// {P} {P}// {P} / \ / \// / \ r-rotate(S) [N] <C> repaint [N] [C]// [N] [S] ==========> \ ======> \// / \ [S] <S>// <C> [D] \ \// [D] [D]// clang-format on// Step 1rotateOppositeDirection(sibling,direction);// Step 2closeNephew->color=Node::BLACK;sibling->color=Node::RED;// Update sibling and nephews after rotationsibling=node->sibling();closeNephew=direction==Direction::LEFT?sibling->left:sibling->right;distantNephew=direction==Direction::LEFT?sibling->right:sibling->left;// Step 3: vvv
Case 5
兄弟节点是黑色,且 close nephew 节点 C 为红色,distant nephew 节点 D 为黑色,父节点既可为红色又可为黑色。此时性质 4 无法满足,通过旋转操作使得黑色节点 S 变为该子树的根节点再进行染色即可满足性质 4。具体步骤如下:
若 N 为左子节点,左旋 P,反之右旋 P。
交换父节点 P 和兄弟节点 S 的颜色,此时性质 3 可能被打破。
将 distant nephew 节点 D 染黑,同时保证了性质 3 和 4。
实现
1 2 3 4 5 6 7 8 91011121314151617181920212223
// clang-format off// Case 5: Sibling is BLACK, close nephew is BLACK,// distant nephew is RED// Step 1. If N is a left child, left rotate P;// If N is a right child, right rotate P.// Step 2. Swap the color of parent and sibling.// Step 3. Paint distant nephew D to BLACK.// {P} [S] {S}// / \ l-rotate(P) / \ repaint / \// [N] [S] ==========> {P} <D> ======> [P] [D]// / \ / \ / \// [C] <D> [N] [C] [N] [C]// clang-format onassert(closeNephew==nullptr||closeNephew->isBlack());assert(distantNephew->isRed());// Step 1rotateSameDirection(node->parent,direction);// Step 2sibling->color=node->parent->color;node->parent->color=Node::BLACK;// Step 3distantNephew->color=Node::BLACK;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 树)在结构上是等价的。
虽然二者在结构上是等价的,但这并不意味这二者可以互相取代或者在所有情况下都可以互换使用。最显然的例子就是数据库的索引,由于 B 树不存在旋转操作,因此其所有节点的存储位置都是可以被确定的,这种结构对于不区分堆栈的磁盘来说显然比红黑树动态分配节点存储空间要更加合适。另外一点就是由于 B 树/B+ 树内储存的数据都是连续的,对于有着大量连续查询需求的数据库来说更加友好。而对于小数据量随机插入/查询的需求,由于 B 树的每个节点都存储了若干条记录,因此发生 cache miss 时就需要将整个节点的所有数据读入缓存中,在这些情况下 BST(红黑树,AVL,Splay 等)则反而会优与 B 树/B+ 树。对这方面内容感兴趣的读者可以去阅读一下 为什么 rust 中的 Map 使用的是 B 树而不是像其他主流语言一样使用红黑树。
Linux 的稳定内核版本在 2.6.24 之后,使用了新的调度程序 CFS,所有非实时可运行进程都以虚拟运行时间为键值用一棵红黑树进行维护,以完成更公平高效地调度所有任务。CFS 弃用 active/expired 数组和动态计算优先级,不再跟踪任务的睡眠时间和区别是否交互任务,而是在调度中采用基于时间计算键值的红黑树来选取下一个任务,根据所有任务占用 CPU 时间的状态来确定调度任务优先级。
/** * @file RBTreeMap.hpp * @brief An RBTree-based map implementation * @details The map is sorted according to the natural ordering of its * keys or by a {@code Compare} function provided; This implementation * provides guaranteed log(n) time cost for the contains, get, insert * and remove operations. * @author [r.ivance](https://github.com/RIvance) */#ifndef RBTREE_MAP_HPP#define RBTREE_MAP_HPP#include<cassert>#include<cstddef>#include<cstdint>#include<functional>#include<memory>#include<stack>#include<utility>#include<vector>/** * An RBTree-based map implementation * https://en.wikipedia.org/wiki/Red–black_tree * * A red–black tree (RBTree) is a kind of self-balancing binary search tree. * Each node stores an extra field representing "color" (RED or BLACK), used * to ensure that the tree remains balanced during insertions and deletions. * * In addition to the requirements imposed on a binary search tree the following * must be satisfied by a red–black tree: * * 1. Every node is either RED or BLACK. * 2. All NIL nodes (`nullptr` in this implementation) are considered BLACK. * 3. A RED node does not have a RED child. * 4. Every path from a given node to any of its descendant NIL nodes goes * through the same number of BLACK nodes. * * @tparam Key the type of keys maintained by this map * @tparam Value the type of mapped values * @tparam Compare the compare function */template<typenameKey,typenameValue,typenameCompare=std::less<Key>>classRBTreeMap{private:usingUSize=size_t;Comparecompare=Compare();public:structEntry{Keykey;Valuevalue;booloperator==(constEntry&rhs)constnoexcept{returnthis->key==rhs.key&&this->value==rhs.value;}booloperator!=(constEntry&rhs)constnoexcept{returnthis->key!=rhs.key||this->value!=rhs.value;}};private:structNode{usingPtr=std::shared_ptr<Node>;usingProvider=conststd::function<Ptr(void)>&;usingConsumer=conststd::function<void(constPtr&)>&;enum{RED,BLACK}color=RED;enumDirection{LEFT=-1,ROOT=0,RIGHT=1};Keykey;Valuevalue{};Ptrparent=nullptr;Ptrleft=nullptr;Ptrright=nullptr;explicitNode(Keyk):key(std::move(k)){}explicitNode(Keyk,Valuev):key(std::move(k)),value(std::move(v)){}~Node()=default;inlineboolisLeaf()constnoexcept{returnthis->left==nullptr&&this->right==nullptr;}inlineboolisRoot()constnoexcept{returnthis->parent==nullptr;}inlineboolisRed()constnoexcept{returnthis->color==RED;}inlineboolisBlack()constnoexcept{returnthis->color==BLACK;}inlineDirectiondirection()constnoexcept{if(this->parent!=nullptr){if(this==this->parent->left.get()){returnDirection::LEFT;}else{returnDirection::RIGHT;}}else{returnDirection::ROOT;}}inlinePtr&sibling()constnoexcept{assert(!this->isRoot());if(this->direction()==LEFT){returnthis->parent->right;}else{returnthis->parent->left;}}inlineboolhasSibling()constnoexcept{return!this->isRoot()&&this->sibling()!=nullptr;}inlinePtr&uncle()constnoexcept{assert(this->parent!=nullptr);returnparent->sibling();}inlineboolhasUncle()constnoexcept{return!this->isRoot()&&this->parent->hasSibling();}inlinePtr&grandParent()constnoexcept{assert(this->parent!=nullptr);returnthis->parent->parent;}inlineboolhasGrandParent()constnoexcept{return!this->isRoot()&&this->parent->parent!=nullptr;}inlinevoidrelease()noexcept{// avoid memory leak caused by circular referencethis->parent=nullptr;if(this->left!=nullptr){this->left->release();}if(this->right!=nullptr){this->right->release();}}inlineEntryentry()const{returnEntry{key,value};}staticPtrfrom(constKey&k){returnstd::make_shared<Node>(Node(k));}staticPtrfrom(constKey&k,constValue&v){returnstd::make_shared<Node>(Node(k,v));}};usingNodePtr=typenameNode::Ptr;usingConstNodePtr=constNodePtr&;usingDirection=typenameNode::Direction;usingNodeProvider=typenameNode::Provider;usingNodeConsumer=typenameNode::Consumer;NodePtrroot=nullptr;USizecount=0;usingK=constKey&;usingV=constValue&;public:usingEntryList=std::vector<Entry>;usingKeyValueConsumer=conststd::function<void(K,V)>&;usingMutKeyValueConsumer=conststd::function<void(K,Value&)>&;usingKeyValueFilter=conststd::function<bool(K,V)>&;classNoSuchMappingException:protectedstd::exception{private:constchar*message;public:explicitNoSuchMappingException(constchar*msg):message(msg){}constchar*what()constnoexceptoverride{returnmessage;}};RBTreeMap()noexcept=default;~RBTreeMap()noexcept{// Unlinking circular references to avoid memory leakthis->clear();}/** * Returns the number of entries in this map. * @return size_t */inlineUSizesize()constnoexcept{returnthis->count;}/** * Returns true if this collection contains no elements. * @return bool */inlineboolempty()constnoexcept{returnthis->count==0;}/** * Removes all of the elements from this map. */voidclear()noexcept{// Unlinking circular references to avoid memory leakif(this->root!=nullptr){this->root->release();this->root=nullptr;}this->count=0;}/** * Returns the value to which the specified key is mapped; If this map * contains no mapping for the key, a {@code NoSuchMappingException} will * be thrown. * @param key * @return RBTreeMap<Key, Value>::Value * @throws NoSuchMappingException */Valueget(Kkey)const{if(this->root==nullptr){throwNoSuchMappingException("Invalid key");}else{NodePtrnode=this->getNode(this->root,key);if(node!=nullptr){returnnode->value;}else{throwNoSuchMappingException("Invalid key");}}}/** * Returns the value to which the specified key is mapped; If this map * contains no mapping for the key, a new mapping with a default value * will be inserted. * @param key * @return RBTreeMap<Key, Value>::Value & */Value&getOrDefault(Kkey){if(this->root==nullptr){this->root=Node::from(key);this->root->color=Node::BLACK;this->count+=1;returnthis->root->value;}else{returnthis->getNodeOrProvide(this->root,key,[&key](){returnNode::from(key);})->value;}}/** * Returns true if this map contains a mapping for the specified key. * @param key * @return bool */boolcontains(Kkey)const{returnthis->getNode(this->root,key)!=nullptr;}/** * Associates the specified value with the specified key in this map. * @param key * @param value */voidinsert(Kkey,Vvalue){if(this->root==nullptr){this->root=Node::from(key,value);this->root->color=Node::BLACK;this->count+=1;}else{this->insert(this->root,key,value);}}/** * If the specified key is not already associated with a value, associates * it with the given value and returns true, else returns false. * @param key * @param value * @return bool */boolinsertIfAbsent(Kkey,Vvalue){USizesizeBeforeInsertion=this->size();if(this->root==nullptr){this->root=Node::from(key,value);this->root->color=Node::BLACK;this->count+=1;}else{this->insert(this->root,key,value,false);}returnthis->size()>sizeBeforeInsertion;}/** * If the specified key is not already associated with a value, associates * it with the given value and returns the value, else returns the associated * value. * @param key * @param value * @return RBTreeMap<Key, Value>::Value & */Value&getOrInsert(Kkey,Vvalue){if(this->root==nullptr){this->root=Node::from(key,value);this->root->color=Node::BLACK;this->count+=1;returnroot->value;}else{NodePtrnode=getNodeOrProvide(this->root,key,[&](){returnNode::from(key,value);});returnnode->value;}}Valueoperator[](Kkey)const{returnthis->get(key);}Value&operator[](Kkey){returnthis->getOrDefault(key);}/** * Removes the mapping for a key from this map if it is present; * Returns true if the mapping is present else returns false * @param key the key of the mapping * @return bool */boolremove(Kkey){if(this->root==nullptr){returnfalse;}else{returnthis->remove(this->root,key,[](ConstNodePtr){});}}/** * Removes the mapping for a key from this map if it is present and returns * the value which is mapped to the key; If this map contains no mapping for * the key, a {@code NoSuchMappingException} will be thrown. * @param key * @return RBTreeMap<Key, Value>::Value * @throws NoSuchMappingException */ValuegetAndRemove(Kkey){Valueresult;NodeConsumeraction=[&](ConstNodePtrnode){result=node->value;};if(root==nullptr){throwNoSuchMappingException("Invalid key");}else{if(remove(this->root,key,action)){returnresult;}else{throwNoSuchMappingException("Invalid key");}}}/** * Gets the entry corresponding to the specified key; if no such entry * exists, returns the entry for the least key greater than the specified * key; if no such entry exists (i.e., the greatest key in the Tree is less * than the specified key), a {@code NoSuchMappingException} will be thrown. * @param key * @return RBTreeMap<Key, Value>::Entry * @throws NoSuchMappingException */EntrygetCeilingEntry(Kkey)const{if(this->root==nullptr){throwNoSuchMappingException("No ceiling entry in this map");}NodePtrnode=this->root;while(node!=nullptr){if(key==node->key){returnnode->entry();}if(compare(key,node->key)){/* key < node->key */if(node->left!=nullptr){node=node->left;}else{returnnode->entry();}}else{/* key > node->key */if(node->right!=nullptr){node=node->right;}else{while(node->direction()==Direction::RIGHT){if(node!=nullptr){node=node->parent;}else{throwNoSuchMappingException("No ceiling entry exists in this map");}}if(node->parent==nullptr){throwNoSuchMappingException("No ceiling entry exists in this map");}returnnode->parent->entry();}}}throwNoSuchMappingException("No ceiling entry in this map");}/** * Gets the entry corresponding to the specified key; if no such entry exists, * returns the entry for the greatest key less than the specified key; * if no such entry exists, a {@code NoSuchMappingException} will be thrown. * @param key * @return RBTreeMap<Key, Value>::Entry * @throws NoSuchMappingException */EntrygetFloorEntry(Kkey)const{if(this->root==nullptr){throwNoSuchMappingException("No floor entry exists in this map");}NodePtrnode=this->root;while(node!=nullptr){if(key==node->key){returnnode->entry();}if(compare(key,node->key)){/* key < node->key */if(node->left!=nullptr){node=node->left;}else{while(node->direction()==Direction::LEFT){if(node!=nullptr){node=node->parent;}else{throwNoSuchMappingException("No floor entry exists in this map");}}if(node->parent==nullptr){throwNoSuchMappingException("No floor entry exists in this map");}returnnode->parent->entry();}}else{/* key > node->key */if(node->right!=nullptr){node=node->right;}else{returnnode->entry();}}}throwNoSuchMappingException("No floor entry exists in this map");}/** * Gets the entry for the least key greater than the specified * key; if no such entry exists, returns the entry for the least * key greater than the specified key; if no such entry exists, * a {@code NoSuchMappingException} will be thrown. * @param key * @return RBTreeMap<Key, Value>::Entry * @throws NoSuchMappingException */EntrygetHigherEntry(Kkey){if(this->root==nullptr){throwNoSuchMappingException("No higher entry exists in this map");}NodePtrnode=this->root;while(node!=nullptr){if(compare(key,node->key)){/* key < node->key */if(node->left!=nullptr){node=node->left;}else{returnnode->entry();}}else{/* key >= node->key */if(node->right!=nullptr){node=node->right;}else{while(node->direction()==Direction::RIGHT){if(node!=nullptr){node=node->parent;}else{throwNoSuchMappingException("No higher entry exists in this map");}}if(node->parent==nullptr){throwNoSuchMappingException("No higher entry exists in this map");}returnnode->parent->entry();}}}throwNoSuchMappingException("No higher entry exists in this map");}/** * Returns the entry for the greatest key less than the specified key; if * no such entry exists (i.e., the least key in the Tree is greater than * the specified key), a {@code NoSuchMappingException} will be thrown. * @param key * @return RBTreeMap<Key, Value>::Entry * @throws NoSuchMappingException */EntrygetLowerEntry(Kkey)const{if(this->root==nullptr){throwNoSuchMappingException("No lower entry exists in this map");}NodePtrnode=this->root;while(node!=nullptr){if(compare(key,node->key)||key==node->key){/* key <= node->key */if(node->left!=nullptr){node=node->left;}else{while(node->direction()==Direction::LEFT){if(node!=nullptr){node=node->parent;}else{throwNoSuchMappingException("No lower entry exists in this map");}}if(node->parent==nullptr){throwNoSuchMappingException("No lower entry exists in this map");}returnnode->parent->entry();}}else{/* key > node->key */if(node->right!=nullptr){node=node->right;}else{returnnode->entry();}}}throwNoSuchMappingException("No lower entry exists in this map");}/** * Remove all entries that satisfy the filter condition. * @param filter */voidremoveAll(KeyValueFilterfilter){std::vector<Key>keys;this->inorderTraversal([&](ConstNodePtrnode){if(filter(node->key,node->value)){keys.push_back(node->key);}});for(constKey&key:keys){this->remove(key);}}/** * Performs the given action for each key and value entry in this map. * The value is immutable for the action. * @param action */voidforEach(KeyValueConsumeraction)const{this->inorderTraversal([&](ConstNodePtrnode){action(node->key,node->value);});}/** * Performs the given action for each key and value entry in this map. * The value is mutable for the action. * @param action */voidforEachMut(MutKeyValueConsumeraction){this->inorderTraversal([&](ConstNodePtrnode){action(node->key,node->value);});}/** * Returns a list containing all of the entries in this map. * @return RBTreeMap<Key, Value>::EntryList */EntryListtoEntryList()const{EntryListentryList;this->inorderTraversal([&](ConstNodePtrnode){entryList.push_back(node->entry());});returnentryList;}private:staticvoidmaintainRelationship(ConstNodePtrnode){if(node->left!=nullptr){node->left->parent=node;}if(node->right!=nullptr){node->right->parent=node;}}staticvoidswapNode(NodePtr&lhs,NodePtr&rhs){std::swap(lhs->key,rhs->key);std::swap(lhs->value,rhs->value);std::swap(lhs,rhs);}voidrotateLeft(ConstNodePtrnode){// clang-format off// | |// N S// / \ l-rotate(N) / \ // L S ==========> N R// / \ / \ // M R L Massert(node!=nullptr&&node->right!=nullptr);// clang-format onNodePtrparent=node->parent;Directiondirection=node->direction();NodePtrsuccessor=node->right;node->right=successor->left;successor->left=node;maintainRelationship(node);maintainRelationship(successor);switch(direction){caseDirection::ROOT:this->root=successor;break;caseDirection::LEFT:parent->left=successor;break;caseDirection::RIGHT:parent->right=successor;break;}successor->parent=parent;}voidrotateRight(ConstNodePtrnode){// clang-format off// | |// N S// / \ r-rotate(N) / \ // S R ==========> L N// / \ / \ // L M M Rassert(node!=nullptr&&node->left!=nullptr);// clang-format onNodePtrparent=node->parent;Directiondirection=node->direction();NodePtrsuccessor=node->left;node->left=successor->right;successor->right=node;maintainRelationship(node);maintainRelationship(successor);switch(direction){caseDirection::ROOT:this->root=successor;break;caseDirection::LEFT:parent->left=successor;break;caseDirection::RIGHT:parent->right=successor;break;}successor->parent=parent;}inlinevoidrotateSameDirection(ConstNodePtrnode,Directiondirection){assert(direction!=Direction::ROOT);if(direction==Direction::LEFT){rotateLeft(node);}else{rotateRight(node);}}inlinevoidrotateOppositeDirection(ConstNodePtrnode,Directiondirection){assert(direction!=Direction::ROOT);if(direction==Direction::LEFT){rotateRight(node);}else{rotateLeft(node);}}voidmaintainAfterInsert(NodePtrnode){assert(node!=nullptr);if(node->isRoot()){// Case 1: Current node is root (RED)// No need to fix.assert(node->isRed());return;}if(node->parent->isBlack()){// Case 2: Parent is BLACK// No need to fix.return;}if(node->parent->isRoot()){// clang-format off// Case 3: Parent is root and is RED// Paint parent to BLACK.// <P> [P]// | ====> |// <N> <N>// p.s.// `<X>` is a RED node;// `[X]` is a BLACK node (or NIL);// `{X}` is either a RED node or a BLACK node;// clang-format onassert(node->parent->isRed());node->parent->color=Node::BLACK;return;}if(node->hasUncle()&&node->uncle()->isRed()){// clang-format off// Case 4: Both parent and uncle are RED// Paint parent and uncle to BLACK;// Paint grandparent to RED.// [G] <G>// / \ / \ // <P> <U> ====> [P] [U]// / /// <N> <N>// clang-format onassert(node->parent->isRed());node->parent->color=Node::BLACK;node->uncle()->color=Node::BLACK;node->grandParent()->color=Node::RED;maintainAfterInsert(node->grandParent());return;}if(!node->hasUncle()||node->uncle()->isBlack()){// Case 5 & 6: Parent is RED and Uncle is BLACK// p.s. NIL nodes are also considered BLACKassert(!node->isRoot());if(node->direction()!=node->parent->direction()){// clang-format off// Case 5: Current node is the opposite direction as parent// Step 1. If node is a LEFT child, perform l-rotate to parent;// If node is a RIGHT child, perform r-rotate to parent.// Step 2. Goto Case 6.// [G] [G]// / \ rotate(P) / \ // <P> [U] ========> <N> [U]// \ /// <N> <P>// clang-format on// Step 1: RotationNodePtrparent=node->parent;if(node->direction()==Direction::LEFT){rotateRight(node->parent);}else/* node->direction() == Direction::RIGHT */{rotateLeft(node->parent);}node=parent;// Step 2: vvv}// clang-format off// Case 6: Current node is the same direction as parent// Step 1. If node is a LEFT child, perform r-rotate to grandparent;// If node is a RIGHT child, perform l-rotate to grandparent.// Step 2. Paint parent (before rotate) to BLACK;// Paint grandparent (before rotate) to RED.// [G] <P> [P]// / \ rotate(G) / \ repaint / \ // <P> [U] ========> <N> [G] ======> <N> <G>// / \ \ // <N> [U] [U]// clang-format onassert(node->grandParent()!=nullptr);// Step 1if(node->parent->direction()==Direction::LEFT){rotateRight(node->grandParent());}else{rotateLeft(node->grandParent());}// Step 2node->parent->color=Node::BLACK;node->sibling()->color=Node::RED;return;}}NodePtrgetNodeOrProvide(NodePtr&node,Kkey,NodeProviderprovide){assert(node!=nullptr);if(key==node->key){returnnode;}assert(key!=node->key);NodePtrresult;if(compare(key,node->key)){/* key < node->key */if(node->left==nullptr){result=node->left=provide();node->left->parent=node;maintainAfterInsert(node->left);this->count+=1;}else{result=getNodeOrProvide(node->left,key,provide);}}else{/* key > node->key */if(node->right==nullptr){result=node->right=provide();node->right->parent=node;maintainAfterInsert(node->right);this->count+=1;}else{result=getNodeOrProvide(node->right,key,provide);}}returnresult;}NodePtrgetNode(ConstNodePtrnode,Kkey)const{assert(node!=nullptr);if(key==node->key){returnnode;}if(compare(key,node->key)){/* key < node->key */returnnode->left==nullptr?nullptr:getNode(node->left,key);}else{/* key > node->key */returnnode->right==nullptr?nullptr:getNode(node->right,key);}}voidinsert(NodePtr&node,Kkey,Vvalue,boolreplace=true){assert(node!=nullptr);if(key==node->key){if(replace){node->value=value;}return;}assert(key!=node->key);if(compare(key,node->key)){/* key < node->key */if(node->left==nullptr){node->left=Node::from(key,value);node->left->parent=node;maintainAfterInsert(node->left);this->count+=1;}else{insert(node->left,key,value,replace);}}else{/* key > node->key */if(node->right==nullptr){node->right=Node::from(key,value);node->right->parent=node;maintainAfterInsert(node->right);this->count+=1;}else{insert(node->right,key,value,replace);}}}voidmaintainAfterRemove(ConstNodePtrnode){if(node->isRoot()){return;}assert(node->isBlack()&&node->hasSibling());Directiondirection=node->direction();NodePtrsibling=node->sibling();if(sibling->isRed()){// clang-format off// Case 1: Sibling is RED, parent and nephews must be BLACK// Step 1. If N is a left child, left rotate P;// If N is a right child, right rotate P.// Step 2. Paint S to BLACK, P to RED// Step 3. Goto Case 2, 3, 4, 5// [P] <S> [S]// / \ l-rotate(P) / \ repaint / \ // [N] <S> ==========> [P] [D] ======> <P> [D]// / \ / \ / \ // [C] [D] [N] [C] [N] [C]// clang-format onConstNodePtrparent=node->parent;assert(parent!=nullptr&&parent->isBlack());assert(sibling->left!=nullptr&&sibling->left->isBlack());assert(sibling->right!=nullptr&&sibling->right->isBlack());// Step 1rotateSameDirection(node->parent,direction);// Step 2sibling->color=Node::BLACK;parent->color=Node::RED;// Update sibling after rotationsibling=node->sibling();// Step 3: vvv}NodePtrcloseNephew=direction==Direction::LEFT?sibling->left:sibling->right;NodePtrdistantNephew=direction==Direction::LEFT?sibling->right:sibling->left;boolcloseNephewIsBlack=closeNephew==nullptr||closeNephew->isBlack();booldistantNephewIsBlack=distantNephew==nullptr||distantNephew->isBlack();assert(sibling->isBlack());if(closeNephewIsBlack&&distantNephewIsBlack){if(node->parent->isRed()){// clang-format off// Case 2: Sibling and nephews are BLACK, parent is RED// Swap the color of P and S// <P> [P]// / \ / \ // [N] [S] ====> [N] <S>// / \ / \ // [C] [D] [C] [D]// clang-format onsibling->color=Node::RED;node->parent->color=Node::BLACK;return;}else{// clang-format off// Case 3: Sibling, parent and nephews are all black// Step 1. Paint S to RED// Step 2. Recursively maintain P// [P] [P]// / \ / \ // [N] [S] ====> [N] <S>// / \ / \ // [C] [D] [C] [D]// clang-format onsibling->color=Node::RED;maintainAfterRemove(node->parent);return;}}else{if(closeNephew!=nullptr&&closeNephew->isRed()){// clang-format off// Case 4: Sibling is BLACK, close nephew is RED,// distant nephew is BLACK// Step 1. If N is a left child, right rotate P;// If N is a right child, left rotate P.// Step 2. Swap the color of close nephew and sibling// Step 3. Goto case 5// {P} {P}// {P} / \ / \ // / \ r-rotate(S) [N] <C> repaint [N] [C]// [N] [S] ==========> \ ======> \ // / \ [S] <S>// <C> [D] \ \ // [D] [D]// clang-format on// Step 1rotateOppositeDirection(sibling,direction);// Step 2closeNephew->color=Node::BLACK;sibling->color=Node::RED;// Update sibling and nephews after rotationsibling=node->sibling();closeNephew=direction==Direction::LEFT?sibling->left:sibling->right;distantNephew=direction==Direction::LEFT?sibling->right:sibling->left;// Step 3: vvv}// clang-format off// Case 5: Sibling is BLACK, close nephew is BLACK,// distant nephew is RED// {P} [S]// / \ l-rotate(P) / \ // [N] [S] ==========> {P} <D>// / \ / \ // [C] <D> [N] [C]// clang-format onassert(closeNephew==nullptr||closeNephew->isBlack());assert(distantNephew->isRed());// Step 1rotateSameDirection(node->parent,direction);// Step 2sibling->color=node->parent->color;node->parent->color=Node::BLACK;if(distantNephew!=nullptr){distantNephew->color=Node::BLACK;}return;}}boolremove(NodePtrnode,Kkey,NodeConsumeraction){assert(node!=nullptr);if(key!=node->key){if(compare(key,node->key)){/* key < node->key */NodePtr&left=node->left;if(left!=nullptr&&remove(left,key,action)){maintainRelationship(node);returntrue;}else{returnfalse;}}else{/* key > node->key */NodePtr&right=node->right;if(right!=nullptr&&remove(right,key,action)){maintainRelationship(node);returntrue;}else{returnfalse;}}}assert(key==node->key);action(node);if(this->size()==1){// Current node is the only node of the treethis->clear();returntrue;}if(node->left!=nullptr&&node->right!=nullptr){// clang-format off// Case 1: If the node is strictly internal// Step 1. Find the successor S with the smallest key// and its parent P on the right subtree.// Step 2. Swap the data (key and value) of S and N,// S is the node that will be deleted in place of N.// Step 3. N = S, goto Case 2, 3// | |// N S// / \ / \ // L .. swap(N, S) L ..// | =========> |// P P// / \ / \ // S .. N ..// clang-format on// Step 1NodePtrsuccessor=node->right;NodePtrparent=node;while(successor->left!=nullptr){parent=successor;successor=parent->left;}// Step 2swapNode(node,successor);maintainRelationship(parent);// Step 3: vvv}if(node->isLeaf()){// Current node must not be the rootassert(node->parent!=nullptr);// Case 2: Current node is a leaf// Step 1. Unlink and remove it.// Step 2. If N is BLACK, maintain N;// If N is RED, do nothing.// The maintain operation won't change the node itself,// so we can perform maintain operation before unlink the node.if(node->isBlack()){maintainAfterRemove(node);}if(node->direction()==Direction::LEFT){node->parent->left=nullptr;}else/* node->direction() == Direction::RIGHT */{node->parent->right=nullptr;}}else/* !node->isLeaf() */{assert(node->left==nullptr||node->right==nullptr);// Case 3: Current node has a single left or right child// Step 1. Replace N with its child// Step 2. If N is BLACK, maintain NNodePtrparent=node->parent;NodePtrreplacement=(node->left!=nullptr?node->left:node->right);switch(node->direction()){caseDirection::ROOT:this->root=replacement;break;caseDirection::LEFT:parent->left=replacement;break;caseDirection::RIGHT:parent->right=replacement;break;}if(!node->isRoot()){replacement->parent=parent;}if(node->isBlack()){if(replacement->isRed()){replacement->color=Node::BLACK;}else{maintainAfterRemove(replacement);}}}this->count-=1;returntrue;}voidinorderTraversal(NodeConsumeraction)const{if(this->root==nullptr){return;}std::stack<NodePtr>stack;NodePtrnode=this->root;while(node!=nullptr||!stack.empty()){while(node!=nullptr){stack.push(node);node=node->left;}if(!stack.empty()){node=stack.top();stack.pop();action(node);node=node->right;}}}};#endif // RBTREE_MAP_HPP