The Left-Leaning Red-Black Tree is a variant of the Red-Black Tree that imposes additional restrictions on the positions of red edges (nodes), enabling its insertion and deletion operations to have a one-to-one correspondence with the 2-3 tree.
We assume the reader is already familiar with at least one rotation-based balanced tree, so this article will not explain rotation operations.
Red-Black Tree
Properties
A red-black tree satisfies the following properties:
Every node is either red or black.
NIL nodes (empty leaf nodes) are black.
All children of a red node must be black, meaning no two consecutive red nodes can appear on any path from a leaf to the root.
Every simple path from any node to each leaf in its subtree contains the same number of black nodes. (Black-height balance)
These properties ensure that the longest path from the root to any leaf (alternating red and black) is at most twice as long as the shortest path (all black), thereby maintaining the tree's balance.
Maintaining these properties is relatively complex. If we insert a node, it must initially be colored red; otherwise, property 4 would be violated. Even so, we might still violate property 3, requiring adjustments. Deletion is even more troublesome: similar to insertion, we cannot delete a black node directly, as it would disrupt the black-height balance. How can we conveniently solve these problems?
Left-Leaning Red-Black Tree (LLRB Tree)
Explanation
The Left-Leaning Red-Black Tree is an easier-to-implement variant of the red-black tree.
In the following LLRB tree diagrams, the edges have colors rather than the nodes. By convention, we refer to a node's color as the color of the edge connecting it to its parent.
The LLRB tree imposes an additional restriction on the red-black tree: for any black node, its left and right children must satisfy one of the following:
Both children are black;
The left child is red, and the right child is black.
Valid cases:
Invalid cases:
This is the "left-leaning" property: red edges can only lean to the left.
Process
Insertion
We first use the standard BST insertion method to insert a red leaf node at the bottom of the tree. Then, through bottom-up adjustments, we ensure the tree still satisfies the LLRB tree properties after insertion. The adjustment process is described below:
After insertion, a right-leaning red edge may appear, so we perform a left rotation to fix the right-leaning red edge:
After the left rotation, two consecutive left-leaning red edges may appear:
Thus, we need to perform a right rotation. After the right rotation, we should perform a color_flip: i.e., flip the colors of this node and its two children.
template<classKey,classCompare>typenameSet<Key,Compare>::Node*Set<Key,Compare>::fix_up(Set::Node*root)const{if(is_red(root->rc)&&!is_red(root->lc))// fix right leaned red linkroot=rotate_left(root);if(is_red(root->lc)&&is_red(root->lc->lc))// fix doubly linked left leaned red link// if (root->lc == nullptr), then the second expr won't be evaluatedroot=rotate_right(root);if(is_red(root->lc)&&is_red(root->rc))// break up 4 nodecolor_flip(root);root->size=size(root->lc)+size(root->rc)+1;returnroot;}template<classKey,classCompare>typenameSet<Key,Compare>::Node_Set<Key,Compare>::insert(Set::Node_root,constKey&key)const{if(root==nullptr)returnnewNode(key,kRed,1);if(root->key==key);elseif(cmp\_(key,root->key))// if (key < root->key)root->lc=insert(root->lc,key);elseroot->rc=insert(root->rc,key);returnfix_up(root);}
Deletion
The deletion operation is based on the idea that we cannot delete a black node because it would break the black-height. Therefore, we need to ensure that the node we finally delete is red.
Deleting the Minimum Node
First, let's try deleting the minimum node in the entire tree.
How can we ensure the final deleted node is red? We need to maintain an invariant during the downward recursion: if the current node is h, then we must ensure that h is red, or h->lc is red.
Consider the correctness of this approach: if we can successfully maintain this invariant through various rotations and color flips, then when we reach the minimum node h_min, we have that h_min is red, or h_min's left subtree—but h_min has no left subtree at all! This guarantees that the minimum node must be red. Since it is red, we can safely delete it, and then adjust the tree using the same adjustment logic as the insertion operation.
Now, let's consider how to satisfy this invariant. Note that we will temporarily break some properties of the LLRB tree during the downward recursion, but we will restore them when returning from the recursion.
As shown in the following diagram, this is a simpler case where h->rc->lc is black; we only need a single color flip:
Moreover, after the flip as shown above, it will not create consecutive red edges between h->rc and h->rc->lc.
However, if h->rc->lc is red, the situation becomes more complex:
If we only perform a color flip, consecutive red edges will appear. Considering that we cannot fix such a situation when returning from recursion, we need to handle it differently.
template<classKey,classCompare>typenameSet<Key,Compare>::Node*Set<Key,Compare>::move_red_left(Set::Node*root)const{color_flip(root);if(is_red(root->rc->lc)){// assume that root->rc != nullptr when calling this functionroot->rc=rotate_right(root->rc);root=rotate_left(root);color_flip(root);}returnroot;}template<classKey,classCompare>typenameSet<Key,Compare>::Node*Set<Key,Compare>::delete_min(Set::Node*root)const{if(root->lc==nullptr){deleteroot;returnnullptr;}if(!is_red(root->lc)&&!is_red(root->lc->lc)){// make sure either root->lc or root->lc->lc is red// thus make sure we will delete a red node in the endroot=move_red_left(root);}root->lc=delete_min(root->lc);returnfix_up(root);}
Deleting an Arbitrary Node
We first consider deleting a leaf: similar to deleting the minimum, we also need to maintain an invariant during the deletion of an arbitrary value. However, this time it's more special because we are not only moving left but can go in both left and right directions. Therefore, the invariant maintained during deletion is: if moving left, the current node is h, then we must ensure h is red, or h->lc is red; if moving right, the current node is h, then we must ensure h is red, or h->rc is red. This ensures we will eventually delete a red node.
Now consider deleting a non-leaf node. We only need to find the minimum node in its right subtree (if it exists), replace the node's value with the minimum node's value from the right subtree, and finally delete that minimum node from the right subtree.
What if there is no right subtree? We need to rotate the left subtree over, which avoids this problem.
template<classKey,classCompare>typenameSet<Key,Compare>::Node*Set<Key,Compare>::delete_arbitrary(Set::Node*root,Keykey)const{if(cmp_(key,root->key)){// key < root->keyif(!is_red(root->lc)&&!(is_red(root->lc->lc)))root=move_red_left(root);// ensure the invariant: either root->lc or root->lc->lc (or root and// root->lc after dive into the function) is red, to ensure we will// eventually delete a red node. therefore we will not break the black// height balanceroot->lc=delete_arbitrary(root->lc,key);}else{// key >= root->keyif(is_red(root->lc))root=rotate_right(root);if(key==root->key&&root->rc==nullptr){deleteroot;returnnullptr;}if(!is_red(root->rc)&&!is_red(root->rc->lc))root=move_red_right(root);if(key==root->key){root->key=get_min(root->rc);root->rc=delete_min(root->rc);}else{root->rc=delete_arbitrary(root->rc,key);}}returnfix_up(root);}
Implementation
The following code implements a Set (ordered unique set) using a Left-Leaning Red-Black Tree:
#include<algorithm>#include<memory>#include<vector>template<classKey,classCompare=std::less<Key>>classSet{private:enumNodeColor{kBlack=0,kRed=1};structNode{Keykey;Node*lc{nullptr},*rc{nullptr};size_tsize{0};NodeColorcolor;// the color of the parent linkNode(Keykey,NodeColorcolor,size_tsize):key(key),color(color),size(size){}Node()=default;};voiddestroyTree(Node*root)const{if(root!=nullptr){destroyTree(root->lc);destroyTree(root->rc);root->lc=root->rc=nullptr;deleteroot;}}boolis_red(constNode*nd)const{returnnd==nullptr?false:nd->color;// kRed == 1, kBlack == 0}size_tsize(constNode*nd)const{returnnd==nullptr?0:nd->size;}Node*rotate_left(Node*node)const{// left rotate a red link// <1> <2>// / \\ // \ // * <2> ==> <1> *// / \ / \ // * * * *Node*res=node->rc;node->rc=res->lc;res->lc=node;res->color=node->color;node->color=kRed;res->size=node->size;node->size=size(node->lc)+size(node->rc)+1;returnres;}Node*rotate_right(Node*node)const{// right rotate a red link// <1> <2>// // \ / \\ // <2> * ==> * <1>// / \ / \ // * * * *Node*res=node->lc;node->lc=res->rc;res->rc=node;res->color=node->color;node->color=kRed;res->size=node->size;node->size=size(node->lc)+size(node->rc)+1;returnres;}NodeColorneg_color(NodeColorn)const{returnn==kBlack?kRed:kBlack;}voidcolor_flip(Node*node)const{node->color=neg_color(node->color);node->lc->color=neg_color(node->lc->color);node->rc->color=neg_color(node->rc->color);}Node*insert(Node*root,constKey&key)const;Node*delete_arbitrary(Node*root,Keykey)const;Node*delete_min(Node*root)const;Node*move_red_right(Node*root)const;Node*move_red_left(Node*root)const;Node*fix_up(Node*root)const;constKey&get_min(Node*root)const;voidserialize(Node*root,std::vector<Key>*)const;voidprint_tree(Set::Node*root,intindent)const;Comparecmp_=Compare();Node*root_{nullptr};public:usingKeyType=Key;usingValueType=Key;usingSizeType=std::size_t;usingDifferenceType=std::ptrdiff_t;usingKeyCompare=Compare;usingValueCompare=Compare;usingReference=Key&;usingConstReference=constKey&;Set()=default;Set(Set&)=default;Set(Set&&)noexcept=default;~Set(){destroyTree(root_);}SizeTypesize()const;SizeTypecount(constKeyType&key)const;SizeTypeerase(constKeyType&key);voidclear();voidinsert(constKeyType&key);boolempty()const;std::vector<Key>serialize()const;voidprint_tree()const;};template<classKey,classCompare>typenameSet<Key,Compare>::SizeTypeSet<Key,Compare>::count(ConstReferencekey)const{Node*x=root_;while(x!=nullptr){if(key==x->key)return1;if(cmp_(key,x->key))// if (key < x->key)x=x->lc;elsex=x->rc;}return0;}template<classKey,classCompare>typenameSet<Key,Compare>::SizeTypeSet<Key,Compare>::erase(constKeyType&key){if(count(key)>0){if(!is_red(root_->lc)&&!(is_red(root_->rc)))root_->color=kRed;root_=delete_arbitrary(root_,key);if(root_!=nullptr)root_->color=kBlack;return1;}else{return0;}}template<classKey,classCompare>voidSet<Key,Compare>::clear(){destroyTree(root_);root_=nullptr;}template<classKey,classCompare>voidSet<Key,Compare>::insert(constKeyType&key){root_=insert(root_,key);root_->color=kBlack;}template<classKey,classCompare>boolSet<Key,Compare>::empty()const{returnsize(root_)==0;}template<classKey,classCompare>typenameSet<Key,Compare>::Node*Set<Key,Compare>::insert(Set::Node*root,constKey&key)const{if(root==nullptr)returnnewNode(key,kRed,1);if(root->key==key);elseif(cmp_(key,root->key))// if (key < root->key)root->lc=insert(root->lc,key);elseroot->rc=insert(root->rc,key);returnfix_up(root);}template<classKey,classCompare>typenameSet<Key,Compare>::Node*Set<Key,Compare>::delete_min(Set::Node*root)const{if(root->lc==nullptr){deleteroot;returnnullptr;}if(!is_red(root->lc)&&!is_red(root->lc->lc)){// make sure either root->lc or root->lc->lc is red// thus make sure we will delete a red node in the endroot=move_red_left(root);}root->lc=delete_min(root->lc);returnfix_up(root);}template<classKey,classCompare>typenameSet<Key,Compare>::Node*Set<Key,Compare>::move_red_right(Set::Node*root)const{color_flip(root);if(is_red(root->lc->lc)){// assume that root->lc != nullptr when calling// this functionroot=rotate_right(root);color_flip(root);}returnroot;}template<classKey,classCompare>typenameSet<Key,Compare>::Node*Set<Key,Compare>::move_red_left(Set::Node*root)const{color_flip(root);if(is_red(root->rc->lc)){// assume that root->rc != nullptr when calling this functionroot->rc=rotate_right(root->rc);root=rotate_left(root);color_flip(root);}returnroot;}template<classKey,classCompare>typenameSet<Key,Compare>::Node*Set<Key,Compare>::fix_up(Set::Node*root)const{if(is_red(root->rc)&&!is_red(root->lc))// fix right leaned red linkroot=rotate_left(root);if(is_red(root->lc)&&is_red(root->lc->lc))// fix doubly linked left leaned red link// if (root->lc == nullptr), then the second expr won't be evaluatedroot=rotate_right(root);if(is_red(root->lc)&&is_red(root->rc))// break up 4 nodecolor_flip(root);root->size=size(root->lc)+size(root->rc)+1;returnroot;}template<classKey,classCompare>constKey&Set<Key,Compare>::get_min(Set::Node*root)const{Node*x=root;// will crash as intended when root == nullptrfor(;x->lc!=nullptr;x=x->lc);returnx->key;}template<classKey,classCompare>typenameSet<Key,Compare>::SizeTypeSet<Key,Compare>::size()const{returnsize(root_);}template<classKey,classCompare>typenameSet<Key,Compare>::Node*Set<Key,Compare>::delete_arbitrary(Set::Node*root,Keykey)const{if(cmp_(key,root->key)){// key < root->keyif(!is_red(root->lc)&&!(is_red(root->lc->lc)))root=move_red_left(root);// ensure the invariant: either root->lc or root->lc->lc (or root and// root->lc after dive into the function) is red, to ensure we will// eventually delete a red node. therefore we will not break the black// height balanceroot->lc=delete_arbitrary(root->lc,key);}else{// key >= root->keyif(is_red(root->lc))root=rotate_right(root);if(key==root->key&&root->rc==nullptr){deleteroot;returnnullptr;}if(!is_red(root->rc)&&!is_red(root->rc->lc))root=move_red_right(root);if(key==root->key){root->key=get_min(root->rc);root->rc=delete_min(root->rc);}else{root->rc=delete_arbitrary(root->rc,key);}}returnfix_up(root);}template<classKey,classCompare>std::vector<Key>Set<Key,Compare>::serialize()const{std::vector<int>v;serialize(root_,&v);returnv;}template<classKey,classCompare>voidSet<Key,Compare>::serialize(Set::Node*root,std::vector<Key>*res)const{if(root==nullptr)return;serialize(root->lc,res);res->push_back(root->key);serialize(root->rc,res);}template<classKey,classCompare>voidSet<Key,Compare>::print_tree(Set::Node*root,intindent)const{if(root==nullptr)return;print_tree(root->lc,indent+4);std::cout<<std::string(indent,'-')<<root->key<<std::endl;print_tree(root->rc,indent+4);}template<classKey,classCompare>voidSet<Key,Compare>::print_tree()const{print_tree(root_,0);}
Relationship with 2-3 Trees
A 2-3 tree is a 3rd-order B-tree where each node is either a 2-node or a 3-node, storing one or two data elements. Non-leaf 2-nodes and 3-nodes can only have two or three children, respectively. Moreover, all data stored in a 2-3 tree are ordered.
2-3 trees and left-leaning red-black trees are essentially equivalent. A node in a 2-3 tree can store 1 or 2 elements, while a node in a red-black tree can only store one element. As shown in the following diagrams, a 2-node in a 2-3 tree corresponds to a black node, and a 3-node corresponds to a red node and a black node (consider bc as parallel).
The following diagram shows a left-leaning red-black tree corresponding to a 2-3 tree.
The insertion and deletion operations of 2-3 trees and left-leaning red-black trees have a one-to-one correspondence.1