Red–black tree explained

Red–black tree
Type:Tree
Invented By:Leonidas J. Guibas and Robert Sedgewick
Invented Year:1978
Space Avg:

O(n)

Search Avg:

O(logn)

Search Worst:

O(logn)

Insert Avg:

O(logn)

Insert Worst:

O(logn)

Delete Avg:

O(logn)

Delete Worst:

O(logn)

In computer science, a red–black tree is a self-balancing binary search tree data structure noted for fast storage and retrieval of ordered information. The nodes in a red-black tree hold an extra "color" bit, often drawn as red and black, which help ensure that the tree is always approximately balanced.[1]

When the tree is modified, the new tree is rearranged and "repainted" to restore the coloring properties that constrain how unbalanced the tree can become in the worst case. The properties are designed such that this rearranging and recoloring can be performed efficiently.

The (re-)balancing is not perfect, but guarantees searching in

O(logn)

time, where

n

is the number of entries in the tree. The insert and delete operations, along with tree rearrangement and recoloring, also execute in

O(logn)

time.[2] [3]

Tracking the color of each node requires only one bit of information per node because there are only two colors (due to memory alignment present in some programming languages, the real memory consumption may differ). The tree does not contain any other data specific to it being a red–black tree, so its memory footprint is almost identical to that of a classic (uncolored) binary search tree. In some cases, the added bit of information can be stored at no added memory cost.

History

In 1972, Rudolf Bayer[4] invented a data structure that was a special order-4 case of a B-tree. These trees maintained all paths from root to leaf with the same number of nodes, creating perfectly balanced trees. However, they were not binary search trees. Bayer called them a "symmetric binary B-tree" in his paper and later they became popular as 2–3–4 trees or even 2–3 trees.[5]

In a 1978 paper, "A Dichromatic Framework for Balanced Trees",[6] Leonidas J. Guibas and Robert Sedgewick derived the red–black tree from the symmetric binary B-tree.[7] The color "red" was chosen because it was the best-looking color produced by the color laser printer available to the authors while working at Xerox PARC.[8] Another response from Guibas states that it was because of the red and black pens available to them to draw the trees.[9]

In 1993, Arne Andersson introduced the idea of a right leaning tree to simplify insert and delete operations.[10]

In 1999, Chris Okasaki showed how to make the insert operation purely functional. Its balance function needed to take care of only 4 unbalanced cases and one default balanced case.[11]

The original algorithm used 8 unbalanced cases, but reduced that to 6 unbalanced cases.[1] Sedgewick showed that the insert operation can be implemented in just 46 lines of Java code.[12] [13] In 2008, Sedgewick proposed the left-leaning red–black tree, leveraging Andersson’s idea that simplified the insert and delete operations. Sedgewick originally allowed nodes whose two children are red, making his trees more like 2–3–4 trees, but later this restriction was added, making new trees more like 2–3 trees. Sedgewick implemented the insert algorithm in just 33 lines, significantly shortening his original 46 lines of code.[14] [15]

Terminology

A red–black tree is a special type of binary search tree, used in computer science to organize pieces of comparable data, such as text fragments or numbers (as e.g. the numbers in figures 1 and 2). The nodes carrying keys and/or data are frequently called "internal nodes", but to make this very specific they are also called non-NIL nodes in this article.

The leaf nodes of red–black trees (

 NIL  in figure 1) do not contain keys or data. These "leaves" need not be explicit individuals in computer memory: a NULL pointer can—as in all binary tree data structures— encode the fact that there is no child node at this position in the (parent) node. Nevertheless, by their position in the tree, these objects are in relation to other nodes that is relevant to the RB-structure, it may have parent, sibling (i.e., the other child of the parent), uncle, even nephew node; and may be child—but never parent—of another node.It is not really necessary to attribute a "color" to these end-of-path objects, because the condition "is NIL or BLACK" is implied by the condition "is NIL" (see also this remark).

Figure 2 shows the conceptually same red–black tree without these NIL leaves. To arrive at the same notion of a path, one must notice that e.g., 3 paths run through the node 1, namely a path through 1left plus 2 added paths through 1right, namely the paths through 6left and 6right. This way, these ends of the paths are also docking points for new nodes to be inserted, fully equivalent to the NIL leaves of figure 1.

Instead, to save a marginal amount of execution time, these (possibly many) NIL leaves may be implemented as pointers to one unique (and black) sentinel node (instead of pointers of value NULL).

As a conclusion, the fact that a child does not exist (is not a true node, does not contain data) can in all occurrences be specified by the very same NULL pointer or as the very same pointer to a sentinel node. Throughout this article, either choice is called NIL node and has the constant value NIL.

The black depth of a node is defined as the number of black nodes from the root to that node (i.e. the number of black ancestors). The black height of a red–black tree is the number of black nodes in any path from the root to the leaves, which, by requirement 4, is constant (alternatively, it could be defined as the black depth of any leaf node).[16] The black height of a node is the black height of the subtree rooted by it. In this article, the black height of a NIL node shall be set to 0, because its subtree is empty as suggested by figure 2, and its tree height is also 0.

Properties

In addition to the requirements imposed on a binary search tree the following must be satisfied by a

  1. Every node is either red or black.
  2. All NIL nodes (figure 1) 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.
  5. (Conclusion) If a node N has exactly one child, it must be a red child, because if it were black, its NIL descendants would sit at a different black depth than N's NIL child, violating requirement 4.

Some authors, e.g. Cormen & al., claim "the root is black" as fifth requirement; but not Mehlhorn & Sanders[16] or Sedgewick & Wayne.[15] Since 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.

As an example, every perfect binary tree that consists only of black nodes is a red–black tree.

The read-only operations, such as search or tree traversal, do not affect any of the requirements. In contrast, the modifying operations insert and delete easily maintain requirements 1 and 2, but with respect to the other requirements some extra effort must be made, to avoid introducing a violation of requirement 3, called a red-violation, or of requirement 4, called a black-violation.

The requirements enforce a critical property of red–black trees: the path from the root to the farthest leaf is no more than twice as long as the path from the root to the nearest leaf. The result is that the tree is height-balanced. Since operations such as inserting, deleting, and finding values require worst-case time proportional to the height

h

of the tree, this upper bound on the height allows red–black trees to be efficient in the worst case, namely logarithmic in the number

n

of entries, i.e. which is not the case for ordinary binary search trees. For a mathematical proof see section Proof of bounds.

Red–black trees, like all binary search trees, allow quite efficient sequential access (e.g. in-order traversal, that is: in the order Left–Root–Right) of their elements. But they support also asymptotically optimal direct access via a traversal from root to leaf, resulting in

O(logn)

search time.

Analogy to 2–3–4 trees

Red–black trees are similar in structure to 2–3–4 trees, which are B-trees of order 4.[17] In 2–3–4 trees, each node can contain between 1 and 3 values and have between 2 and 4 children. These 2–3–4 nodes correspond to black node – red children groups in red-black trees, as shown in figure 3. It is not a 1-to-1 correspondence, because 3-nodes have two equivalent representations: the red child may lie either to the left or right. The left-leaning red-black tree variant makes this relationship exactly 1-to-1, by only allowing the left child representation. Since every 2–3–4 node has a corresponding black node, invariant 4 of red-black trees is equivalent to saying that the leaves of a 2–3–4 tree all lie at the same level.

Despite structural similarities, operations on red–black trees are more economical than B-trees. B-trees require management of vectors of variable length, whereas red-black trees are simply binary trees.[18]

Applications and related data structures

Red–black trees offer worst-case guarantees for insertion time, deletion time, and search time. Not only does this make them valuable in time-sensitive applications such as real-time applications, but it makes them valuable building blocks in other data structures that provide worst-case guarantees. For example, many data structures used in computational geometry are based on red–black trees, and the Completely Fair Scheduler and epoll system call of the Linux kernel use red–black trees.[19] [20] The AVL tree is another structure supporting

O(logn)

search, insertion, and removal. AVL trees can be colored red–black, and thus are a subset of red-black trees. The worst-case height of AVL is 0.720 times the worst-case height of red-black trees, so AVL trees are more rigidly balanced. The performance measurements of Ben Pfaff with realistic test cases in 79 runs find AVL to RB ratios between 0.677 and 1.077, median at 0.947, and geometric mean 0.910.[21] The performance of WAVL trees lie in between AVL trees and red-black trees.

Red–black trees are also particularly valuable in functional programming, where they are one of the most common persistent data structures, used to construct associative arrays and sets that can retain previous versions after mutations. The persistent version of red–black trees requires

O(logn)

space for each insertion or deletion, in addition to time.

For every 2–3–4 tree, there are corresponding red–black trees with data elements in the same order. The insertion and deletion operations on 2–3–4 trees are also equivalent to color-flipping and rotations in red–black trees. This makes 2–3–4 trees an important tool for understanding the logic behind red–black trees, and this is why many introductory algorithm texts introduce 2–3–4 trees just before red–black trees, even though 2–3–4 trees are not often used in practice.

In 2008, Sedgewick introduced a simpler version of the red–black tree called the left-leaning red–black tree[22] by eliminating a previously unspecified degree of freedom in the implementation. The LLRB maintains an additional invariant that all red links must lean left except during inserts and deletes. Red–black trees can be made isometric to either 2–3 trees,[23] or 2–3–4 trees,[22] for any sequence of operations. The 2–3–4 tree isometry was described in 1978 by Sedgewick.[6] With 2–3–4 trees, the isometry is resolved by a "color flip," corresponding to a split, in which the red color of two children nodes leaves the children and moves to the parent node.

The original description of the tango tree, a type of tree optimised for fast searches, specifically uses red–black trees as part of its data structure.[24]

As of Java 8, the HashMap has been modified such that instead of using a LinkedList to store different elements with colliding hashcodes, a red–black tree is used. This results in the improvement of time complexity of searching such an element from

O(m)

to

O(logm)

where

m

is the number of elements with colliding hashcodes.[25]

Operations

The read-only operations, such as search or tree traversal, on a red–black tree require no modification from those used for binary search trees, because every red–black tree is a special case of a simple binary search tree. However, the immediate result of an insertion or removal may violate the properties of a red–black tree, the restoration of which is called rebalancing so that red–black trees become self-balancing.It requires in the worst case a small number,

O(logn)

in Big O notation, where

n

is the number of objects in the tree, on average or amortized

O(1)

, a constant number,[26] [16] of color changes (which are very quick in practice); and no more than three tree rotations[27] (two for insertion).

If the example implementation below is not suitable, other implementations with explanations may be found in Ben Pfaff’s[28] annotated C library GNU libavl (v2.0.3 as of June 2019).

The details of the insert and removal operations will be demonstrated with example C++ code, which uses the type definitions, macros below, and the helper function for rotations:

// Basic type definitions:

enum color_t ;

struct RBnode ;

  1. define NIL NULL // null pointer or pointer to sentinel node
  2. define LEFT 0
  3. define RIGHT 1
  4. define left child[LEFT]
  5. define right child[RIGHT]

struct RBtree ;

// Get the child direction (∈)// of the non-root non-NIL RBnode* N:

  1. define childDir(N) (N

(N->parent)->right ? RIGHT : LEFT)

RBnode* RotateDirRoot(RBtree* T, // red–black tree RBnode* P, // root of subtree (may be the root of T) int dir)

  1. define RotateDir(N,dir) RotateDirRoot(T,N,dir)
  2. define RotateLeft(N) RotateDirRoot(T,N,LEFT)
  3. define RotateRight(N) RotateDirRoot(T,N,RIGHT)

Notes to the sample code and diagrams of insertion and removal

The proposal breaks down both, insertion and removal (not mentioning some very simple cases), into six constellations of nodes, edges and colors, which are called cases. The proposal contains for both, insertion and removal, exactly one case that advances one black level closer to the root and loops, the other five cases rebalance the tree of their own. The more complicated cases are pictured in a diagram.

 N  or  N  in the diagrams.
  1. The action "entry" shows the constellation of nodes with their colors which defines a case and mostly violates some of the requirements.
    A blue border rings the current node N and the other nodes are labeled according to their relation to N.
  2. If a rotation is considered useful, this is pictured in the next action, which is labeled "rotation".
  3. If some recoloring is considered useful, this is pictured in the next action, which is labeled "color".[30]
  4. If there is still some need to repair, the cases make use of code of other cases and this after a reassignment of the current node N, which then again carries a blue ring and relative to which other nodes may have to be reassigned also. This action is labeled "reassign".
    For both, insert and delete, there is (exactly) one case which iterates one black level closer to the root; then the reassigned constellation satisfies the respective loop invariant.
Remark
  • For simplicity, the sample code uses the disjunction:
  • U == NIL || U->color == BLACK ''// considered black''
  • and the conjunction:
  • U != NIL && U->color == RED   ''// not considered black''
  • Thereby, it must be kept in mind that both statements are not evaluated in total, if U == NIL. Then in both cases U->color is not touched (see Short-circuit evaluation).
    (The comment considered black is in accordance with requirement 2.)
  • The related if-statements have to occur far less frequently if the proposal[29] is realised.

    Insertion

    Insertion begins by placing the new (non-NIL) node, say N, at the position in the binary search tree of a NIL node whose in-order predecessor’s key compares less than the new node’s key, which in turn compares less than the key of its in-order successor.(Frequently, this positioning is the result of a search within the tree immediately preceding the insert operation and consists of a node P together with a direction dir with The newly inserted node is temporarily colored red so that all paths contain the same number of black nodes as before.But if its parent, say P, is also red then this action introduces a red-violation.

    void RBinsert1(RBtree* T, // -> red–black tree struct RBnode* N, // -> node to be inserted struct RBnode* P, // -> parent node of N (may be NULL) int dir) // side (LEFT or RIGHT) of P where to insert N // end of RBinsert1

    Because the algorithm transforms the input without using an auxiliary data structure and using only a small amount of extra storage space for auxiliary variables it is in-place.

    Removal

    Simple cases

    - When the deleted node has 2 children (non-NIL), then we can swap its value with its in-order successor (the leftmost child of the right subtree), and then delete the successor instead. Since the successor is leftmost, it can only have a right child (non-NIL) or no child at all.

    - When the deleted node has only 1 child (non-NIL). In this case, just replace the node with its child, and color it black.
    The single child (non-NIL) must be red according to conclusion 5, and the deleted node must be black according to requirement 3.

    - When the deleted node has no children (both NIL) and is the root, replace it with NIL. The tree is empty.

    - When the deleted node has no children (both NIL), and is red, simply remove the leaf node.

    - When the deleted node has no children (both NIL), and is black, deleting it will create an imbalance, and requires a fixup, as covered in the next section.

    Removal of a black non-root leaf

    The complex case is when N is not the root, colored black and has no proper child (⇔ only NIL children).In the first iteration, N is replaced by NIL.

    void RBdelete2(RBtree* T, // -> red–black tree struct RBnode* N) // -> node to be deleted // end of RBdelete2

    Because the algorithm transforms the input without using an auxiliary data structure and using only a small amount of extra storage space for auxiliary variables it is in-place.

    Proof of bounds

    For

    h\in\N

    there is a red–black tree of height

    h

    with

    mh

    =2\lfloor(h+1)/2\rfloor+2\lfloor-2

    =l\{

    ||style="vertical-align:top"|

    22\tfrac{h2}-2=2\tfrac{h2+1}-2

    ||       ||style="vertical-align:bot"| if

    h

    even|-|style="vertical-align:top"|

    32\tfrac{h-12}-2

    || ||style="vertical-align:bot"| if

    h

    odd|}nodes (

    \lfloor\rfloor

    is the floor function) and there is no red–black tree of this tree height with fewer nodes—therefore it is minimal.
    Its black height is  

    \lceilh/2\rceil

      (with black root) or for odd

    h

    (then with a red root) also  

    (h-1)/2~.

    ProofFor a red–black tree of a certain height to have minimal number of nodes, it must have exactly one longest path with maximal number of red nodes, to achieve a maximal tree height with a minimal black height. Besides this path all other nodes have to be black. If a node is taken off this tree it either loses height or some RB property.

    The RB tree of height

    h=1

    with red root is minimal. This is in agreement with

    m1=2\lfloor\

    +\!2^ \\!-\\!2 = 2^1\+\!2^0\\!-\\!2 = 1~.

    A minimal RB tree (RBh in figure 4) of height

    h>1

    has a root whose two child subtrees are of different height. The higher child subtree is also a minimal RB tree, containing also a longest path that defines its height it has

    mh-1

    nodes and the black height

    \lfloor(h\

    \!-\\!1)/2\rfloor =: s . The other subtree is a perfect binary tree of (black) height

    s

    having

    2s\

    \!-\\!1=2^\\!-\\!1 black nodes—and no red node. Then the number of nodes is by induction

    mh

    =

    (mh-1)

    +

    (1)

    +

    (2\lfloor(h-1)/2\rfloor-1)

    (higher subtree) (root) (second subtree)
    resulting in

    mh

    =

    (2\lfloor+2\lfloor(h-1)/2\rfloor-2)

    +

    2\lfloor(h-1)/2\rfloor

    =

    2\lfloor+2\lfloor(h+1)/2\rfloor-2

      ■

    The graph of the function

    mh

    is convex and piecewise linear with breakpoints at

    (h=2k

    \;m_=2 \cdot 2^k\!-\2) where

    k\in\N.

    The function has been tabulated as

    mh=

    A027383(h–1) for

    h\geq1

    Solving the function for

    h

    The inequality

    9>8=23

    leads to

    3>23/2

    , which for odd

    h

    leads to

    mh=32(h-1)/2-2=l(3 ⋅ 2-3/2r)2(h+2)/2-2>22h/2-2

    .So in both, the even and the odd case,

    h

    is in the interval

    log2(n+1)

    \leqh\leq

    2log2(n+2)-2=2log2(n/2+1)

    l[<2log2(n+1)r]

    (perfect binary tree) (minimal red–black tree)
    with

    n

    being the number of nodes.[31]
    ConclusionA red–black tree with

    n

    nodes (keys) has tree height

    h\inO(logn).

    Set operations and bulk operations

    In addition to the single-element insert, delete and lookup operations, several set operations have been defined on union, intersection and set difference. Then fast bulk operations on insertions or deletions can be implemented based on these set functions. These set operations rely on two helper operations, Split and Join. With the new operations, the implementation of red–black trees can be more efficient and highly-parallelizable.[32] In order to achieve its time complexities this implementation requires that the root is allowed to be either red or black, and that every node stores its own black height.

    • Join: The function Join is on two red–black trees and and a key, where, i.e. all keys in are less than, and all keys in are greater than . It returns a tree containing all elements in, also as .

    If the two trees have the same black height, Join simply creates a new node with left subtree, root and right subtree . If both and have black root, set to be red. Otherwise is set black.

    If the black heights are unequal, suppose that has larger black height than (the other case is symmetric). Join follows the right spine of until a black node, which is balanced with . At this point a new node with left child, root (set to be red) and right child is created to replace c. The new node may invalidate the red–black invariant because at most three red nodes can appear in a row. This can be fixed with a double rotation. If double red issue propagates to the root, the root is then set to be black, restoring the properties. The cost of this function is the difference of the black heights between the two input trees.

    • Split: To split a red–black tree into two smaller trees, those smaller than key, and those larger than key, first draw a path from the root by inserting into the red–black tree. After this insertion, all values less than will be found on the left of the path, and all values greater than will be found on the right. By applying Join, all the subtrees on the left side are merged bottom-up using keys on the path as intermediate nodes from bottom to top to form the left tree, and the right part is symmetric.

    For some applications, Split also returns a boolean value denoting if appears in the tree. The cost of Split is

    O(logn),

    order of the height of the tree. This algorithm actually has nothing to do with any special properties of a red–black tree, and may be used on any tree with a join operation, such as an AVL tree.

    The join algorithm is as follows:

    function joinRightRB(TL, k, TR): if (TL.color=black) and (TL.blackHeight=TR.blackHeight): return Node(TL,⟨k,red⟩,TR) T'=Node(TL.left,⟨TL.key,TL.color⟩,joinRightRB(TL.right,k,TR)) if (TL.color=black) and (T'.right.color=T'.right.right.color=red): T'.right.right.color=black; return rotateLeft(T') return T' /* T[recte T'] */ function joinLeftRB(TL, k, TR): /* symmetric to joinRightRB */ function join(TL, k, TR): if TL.blackHeight>TR.blackHeight: T'=joinRightRB(TL,k,TR) if (T'.color=red) and (T'.right.color=red): T'.color=black return T' if TR.blackHeight>TL.blackHeight: /* symmetric */ if (TL.color=black) and (TR.color=black): return Node(TL,⟨k,red⟩,TR) return Node(TL,⟨k,black⟩,TR)

    The split algorithm is as follows:

    function split(T, k): if (T = nil) return (nil, false, nil) if (k = T.key) return (T.left, true, T.right) if (k < T.key): (L',b,R') = split(T.left, k) return (L',b,join(R',T.key,T.right)) (L',b,R') = split(T.right, k) return (join(T.left,T.key,L'),b,T.right)

    The union of two red–black trees and representing sets and, is a red–black tree that represents . The following recursive function computes this union:

    function union(t1, t2): if t1 = nil return t2 if t2 = nil return t1 (L1,b,R1)=split(t1,t2.key) proc1=start: TL=union(L1,t2.left) proc2=start: TR=union(R1,t2.right) wait all proc1,proc2 return join(TL, t2.key, TR)

    Here, split is presumed to return two trees: one holding the keys less its input key, one holding the greater keys. (The algorithm is non-destructive, but an in-place destructive version exists also.)

    The algorithm for intersection or difference is similar, but requires the Join2 helper routine that is the same as Join but without the middle key. Based on the new functions for union, intersection or difference, either one key or multiple keys can be inserted to or deleted from the red–black tree. Since Split calls Join but does not deal with the balancing criteria of red–black trees directly, such an implementation is usually called the "join-based" implementation.

    The complexity of each of union, intersection and difference is

    O\left(mlog\left({n\overm}+1\right)\right)

    for two red–black trees of sizes

    m

    and

    n(\gem)

    . This complexity is optimal in terms of the number of comparisons. More importantly, since the recursive calls to union, intersection or difference are independent of each other, they can be executed in parallel with a parallel depth

    O(logmlogn)

    . When

    m=1

    , the join-based implementation has the same computational directed acyclic graph (DAG) as single-element insertion and deletion if the root of the larger tree is used to split the smaller tree.

    Parallel algorithms

    Parallel algorithms for constructing red–black trees from sorted lists of items can run in constant time or

    O(loglogn)

    time, depending on the computer model, if the number of processors available is asymptotically proportional to the number

    n

    of items where

    n\toinfty

    . Fast search, insertion, and deletion parallel algorithms are also known.[33]

    The join-based algorithms for red–black trees are parallel for bulk operations, including union, intersection, construction, filter, map-reduce, and so on.

    Parallel bulk operations

    Basic operations like insertion, removal or update can be parallelised by defining operations that process bulks of multiple elements. It is also possible to process bulks with several basic operations, for example bulks may contain elements to insert and also elements to remove from the tree.

    The algorithms for bulk operations aren't just applicable to the red–black tree, but can be adapted to other sorted sequence data structures also, like the 2–3 tree, 2–3–4 tree and (a,b)-tree. In the following different algorithms for bulk insert will be explained, but the same algorithms can also be applied to removal and update. Bulk insert is an operation that inserts each element of a sequence

    I

    into a tree

    T

    .

    Join-based

    This approach can be applied to every sorted sequence data structure that supports efficient join- and split-operations.[34] The general idea is to split

    I

    and

    T

    in multiple parts and perform the insertions on these parts in parallel.
    1. First the bulk

    I

    of elements to insert must be sorted.
    1. After that, the algorithm splits

    I

    into

    k\inN+

    parts

    \langleI1,,Ik\rangle

    of about equal sizes.
    1. Next the tree

    T

    must be split into

    k

    parts

    \langleT1,,Tk\rangle

    in a way, so that for every

    j\inN+

    \, 1 \leq j < k following constraints hold:

    last(Ij)<first(Tj)

    last(Tj)<first(Ij)

    1. Now the algorithm inserts each element of

    Ij

    into

    Tj

    sequentially. This step must be performed for every

    j

    , which can be done by up to

    k

    processors in parallel.
    1. Finally, the resulting trees will be joined to form the final result of the entire operation.

    Note that in Step 3 the constraints for splitting

    I

    assure that in Step 5 the trees can be joined again and the resulting sequence is sorted.
    initial treeBulkInsert JoinBased SplitTree.svgsplit I and TBulkInsert JoinBased SplitTreeInserted.svginsert into the split TBulkInsert JoinBased JoinedTree.svgjoin T

    The pseudo code shows a simple divide-and-conquer implementation of the join-based algorithm for bulk-insert.Both recursive calls can be executed in parallel.The join operation used here differs from the version explained in this article, instead join2 is used, which misses the second parameter k.

    bulkInsert(T, I, k): I.sort bulklInsertRec(T, I, k) bulkInsertRec(T, I, k): if k = 1: forall e in I: T.insert(e) else m := ⌊size(I) / 2⌋ (T1, _, T2) := split(T, I[m]) bulkInsertRec(T1, I[0 .. m], ⌈k / 2⌉)

    bulkInsertRec(T2, I[m + 1 .. size(I) - 1], ⌊k / 2⌋) T ← join2(T1, T2)
    Execution time

    Sorting

    I

    is not considered in this analysis.
    1. recursion levels

    \inO(logk)

    T(split) + T(join)

    \inO(log

    T)
    insertions per thread

    \inO\left(

    |I|
    k

    \right)

    T(insert)

    \inO(log

    T)
    T(bulkInsert) with

    k

    = #processors

    \inO\left(logklog

    T+ \frac
    \log
    T\right)
    This can be improved by using parallel algorithms for splitting and joining.In this case the execution time is

    \inO\left(log

    T+ \frac
    \log
    T\right).[35]
    Work
    1. splits, #joins

    \inO(k)

    W(split) + W(join)

    \inO(log

    T)
    1. insertions

    \inO(

    I)
    W(insert)

    \inO(log

    T)
    W(bulkInsert)

    \inO(klog

    T+ I\log T)

    Pipelining

    Another method of parallelizing bulk operations is to use a pipelining approach.[36] This can be done by breaking the task of processing a basic operation up into a sequence of subtasks.For multiple basic operations the subtasks can be processed in parallel by assigning each subtask to a separate processor.

    1. First the bulk

    I

    of elements to insert must be sorted.
    1. For each element in

    I

    the algorithm locates the according insertion position in

    T

    . This can be done in parallel for each element

    \inI

    since

    T

    won't be mutated in this process. Now

    I

    must be divided into subsequences

    S

    according to the insertion position of each element. For example

    sn,

    is the subsequence of

    I

    that contains the elements whose insertion position would be to the left of node

    n

    .
    1. The middle element

    mn,

    of every subsequence

    sn,

    will be inserted into

    T

    as a new node

    n'

    . This can be done in parallel for each

    mn,

    since by definition the insertion position of each

    mn,

    is unique. If

    sn,

    contains elements to the left or to the right of

    mn,

    , those will be contained in a new set of subsequences

    S

    as

    sn',

    or

    sn',

    .
    1. Now

    T

    possibly contains up to two consecutive red nodes at the end of the paths form the root to the leaves, which needs to be repaired. Note that, while repairing, the insertion position of elements

    \inS

    have to be updated, if the corresponding nodes are affected by rotations.
    If two nodes have different nearest black ancestors, they can be repaired in parallel. Since at most four nodes can have the same nearest black ancestor, the nodes at the lowest level can be repaired in a constant number of parallel steps.
    This step will be applied successively to the black levels above until

    T

    is fully repaired.
    1. The steps 3 to 5 will be repeated on the new subsequences until

    S

    is empty. At this point every element

    \inI

    has been inserted. Each application of these steps is called a stage. Since the length of the subsequences in

    S

    is

    \inO(

    I) and in every stage the subsequences are being cut in half, the number of stages is

    \inO(log

    I).
    Since all stages move up the black levels of the tree, they can be parallelised in a pipeline. Once a stage has finished processing one black level, the next stage is able to move up and continue at that level.
    Initial treeBulkInsert Pipelining InsertPositions.svgFind insert positionsBulkInsert Pipelining Stage1Insert.svgStage 1 inserts elementsBulkInsert Pipelining Stage1Repair.svgStage 1 begins to repair nodesBulkInsert Pipelining Stage2Insert.svgStage 2 inserts elementsBulkInsert Pipelining Stage2Repair.svgStage 2 begins to repair nodesBulkInsert Pipelining Stage3Insert.svgStage 3 inserts elementsBulkInsert Pipelining Stage3Repair1.svgStage 3 begins to repair nodesBulkInsert Pipelining Stage3Repair2.svgStage 3 continues to repair nodes
    Execution time

    Sorting

    I

    is not considered in this analysis.Also,
    I is assumed to be smaller than
    T, otherwise it would be more efficient to construct the resulting tree from scratch.
    T(find insert position)

    \inO(log

    T)
    1. stages

    \inO(log

    I)
    T(insert) + T(repair)

    \inO(log

    T)
    T(bulkInsert) with
    I ~ #processors

    \inO(log

    I+ 2 \cdot \log T)

    =O(log

    T)
    Work
    W(find insert positions)

    \inO(

    I\log T)
    1. insertions, #repairs

    \inO(

    I)
    W(insert) + W(repair)

    \inO(log

    T)
    W(bulkInsert)

    \inO(2

    I\log T)

    =O(

    I\log T)

    See also

    Further reading

    External links

    Notes and References

    1. Book: Cormen . Thomas H. . Thomas H. Cormen . Leiserson . Charles E. . Charles E. Leiserson . Rivest . Ronald L. . Ronald L. Rivest . Stein . Clifford . Clifford Stein . 2001 . Introduction to Algorithms . 2nd . 978-0-262-03293-3 . Red - Black Trees . 273–301 . Introduction to Algorithms . MIT Press.
    2. Web site: Paton . James . Red–Black Trees .
    3. Web site: Red–Black Trees . John . Morris . 1998 . Data Structures and Algorithms.
    4. Bayer . Rudolf. 1972. Symmetric binary B-Trees: Data structure and maintenance algorithms. Acta Informatica. 1. 4. 290–306. 10.1007/BF00289509. 28836825.
    5. Book: Drozdek, Adam . Data Structures and Algorithms in Java . Sams Publishing . 2001 . 978-0534376680 . 323 . 2.
    6. Guibas . Leonidas J. . Leonidas J. Guibas . Sedgewick . Robert . Robert Sedgewick (computer scientist) . A Dichromatic Framework for Balanced Trees . Proceedings of the 19th Annual Symposium on Foundations of Computer Science . 1978 . 8–21 . 10.1109/SFCS.1978.3.
    7. Web site: Red Black Trees. eternallyconfuzzled.com. 2015-09-02. https://web.archive.org/web/20070927222509/http://eternallyconfuzzled.com/tuts/datastructures/jsw_tut_rbtree.aspx. 2007-09-27. dead.
    8. Sedgewick . Robert . Robert Sedgewick (computer scientist) . 2012 . Red–Black BSTs . Coursera . A lot of people ask why did we use the name red–black. Well, we invented this data structure, this way of looking at balanced trees, at Xerox PARC that was the home of the personal computer and many other innovations that we live with today entering[sic] graphic user interfaces, Ethernet and object-oriented programmings[sic] and many other things. But one of the things that was invented there was laser printing and we were very excited to have nearby color laser printer that could print things out in color and out of the colors the red looked the best. So, that's why we picked the color red to distinguish red links, the types of links, in three nodes. So, that's an answer to the question for people that have been asking..
    9. Web site: Where does the term "Red/Black Tree" come from?. programmers.stackexchange.com. 2015-09-02.
    10. Book: Andersson , Arne . Balanced search trees made simple. Lecture Notes in Computer Science. Proceedings. Springer-Verlag Berlin Heidelberg. 1993-08-11. 978-3-540-57155-1. 10.1007/3-540-57155-8_236. 60–71 . 709. Frank . Dehne. Jörg-Rüdiger. Sack. Nicola. Santoro. Sue. Whitesides. https://www.springer.com/la/book/9783540571551. Algorithms and Data Structures. https://web.archive.org/web/20181208183054/https://www.springer.com/la/book/9783540571551. 2018-12-08. 10.1.1.118.6192. Alt URL
    11. Red–black trees in a functional setting . Journal of Functional Programming . 1999-01-01 . 10.1017/S0956796899003494 . 1469-7653 . 471–477 . 9 . 4 . Chris . Okasaki . 20298262 . free .
    12. Book: Sedgewick , Robert . Robert Sedgewick (computer scientist). Algorithms. Addison-Wesley. 1st. 1983. 978-0-201-06672-2. registration.
    13. Web site: RedBlackBST.java. Sedgewick. Robert. Robert Sedgewick (computer scientist). Wayne. Kevin. algs4.cs.princeton.edu. 7 April 2018.
    14. Web site: Left-leaning Red–Black Trees. Sedgewick. Robert. Robert Sedgewick (computer scientist). 2008.
    15. Book: Sedgewick. Robert. Robert Sedgewick (computer scientist). Wayne. Kevin. Algorithms. 4th. 978-0-321-57351-3. 2011. Addison-Wesley Professional.
    16. Book: 7. Sorted Sequences. http://people.mpi-inf.mpg.de/~mehlhorn/ftp/Toolbox/SortedSequences.pdf. Algorithms and Data Structures: The Basic Toolbox. Mehlhorn . Kurt . Kurt Mehlhorn. Sanders. Peter . Peter Sanders (computer scientist). Springer . Berlin/Heidelberg. 2008. 978-3-540-77977-3. 10.1007/978-3-540-77978-0 . 10.1.1.148.2305.
    17. Using Knuth’s definition of order: the maximum number of children
    18. Book: Sedgewick, Robert . Robert Sedgewick (computer scientist) . Algorithms in C++ . Addison-Wesley Professional . 1998 . 978-0-201-35088-3 . 565–575 . limited.
    19. Web site: IBM Developer . developer.ibm.com . 25 May 2024.
    20. Web site: The Implementation of epoll (1). September 2014.
    21. [#Pfaff b|Pfaff 2004]
    22. Web site: Robert Sedgewick. Cs.princeton.edu. 4 June 2020 . 26 March 2022.
    23. Web site: Balanced Trees. Cs.princeton.edu. 26 March 2022.
    24. 10.1137/S0097539705447347. Dynamic Optimality—Almost. SIAM Journal on Computing. 37. 1 . 240. 2007. Demaine . E. D. . Harmon . D. . Iacono . J. . Pătraşcu . M. . 1480961.
    25. Web site: How does a HashMap work in JAVA . coding-geek.com.
    26. Tarjan. Robert Endre. Robert Tarjan. Amortized Computational Complexity. SIAM Journal on Algebraic and Discrete Methods. April 1985. 6. 2. 306–318. 10.1137/0606031.
    27. The important thing about these tree rotations is that they preserve the in-order sequence of the tree’s nodes.
    28. Web site: Ben Pfaff (2007): Online HTML version of a well-documented collection of binary search tree and balanced tree library routines.
    29. The left columns contain far less nodes than the right ones, especially for removal. This indicates that some efficiency can be gained by pulling the first iteration out of the rebalancing loops of insertion and deletion, because many of the named nodes are NIL nodes in the first iteration and definitively non-NIL later. (See also this remark.)
    30. Rotations have been placed before recoloring for reasons of clarity. But the two commute, so that it is free choice to move the rotation to the tail.
    31. Equality at the upper bound holds for the minimal RB trees RB2k of even height

      2k

      with

      n=22k-2

      nodes and only for those. So the inequality is marginally more precise than the widespread

      h<2log2(n+1),

      e.g. in Cormen p. 264.
      Moreover, these trees are binary trees that admit one and only one coloring conforming to the RB requirements 1 to 4. But there are further such trees, e.g. appending a child node to a black leaf always forces it to red. (A minimal RB tree of odd height allows to flip the root’s color from red to black.)
    32. .
    33. Theoretical Computer Science . Parallel algorithms for red–black trees . Heejin . Park . Kunsoo . Park . 262 . 1–2 . 415–435 . 2001 . 10.1016/S0304-3975(00)00287-5 . Our parallel algorithm for constructing a red–black tree from a sorted list of

      n

      items runs in

      O(1)

      time with

      n

      processors on the CRCW PRAM and runs in

      O(loglogn)

      time with

      n/loglogn

      processors on the EREW PRAM. . free .
    34. Book: Sanders , Peter . Mehlhorn . Kurt . Dietzfelbinger . Martin . Dementiev . Roman . 2019 . Sequential and Parallel Algorithms and Data Structures : The Basic Toolbox . Springer eBooks . Cham . Springer . 252–253 . 9783030252090. 10.1007/978-3-030-25209-0 . 201692657 .
    35. Fast Parallel Operations on Search Trees . Akhremtsev . Yaroslav . Sanders . Peter . HiPC 2016, the 23rd IEEE International Conference on High Performance Computing, Data, and Analytics, Hyderabad, India, December, 19-22 . 291–300 . IEEE, Piscataway (NJ) . 2016 . 978-1-5090-5411-4 . 1510.05433 . 2015arXiv151005433A .
    36. Book: Jájá , Joseph . An introduction to parallel algorithms . Reading, Mass. [u.a.] . Addison-Wesley . 1992 . 0201548569 . 65–70. 0781.68009 .