Black Trees
Black Trees
• RB1. The root and all external nodes are colored black.
• RB3. All root-to-external-node paths have the same number of black nodes.
10/27/2023 Red-Black Trees 3
Red-Black Trees Insertion
b u b u
v w v w
z z
6-1 6-2
10/27/2023 Red-Black Trees 5
Rotation
• Red child, red parent. Parent no sibling or parent has a black
sibling. a
a
b u
b z
v
v u
7-1 7-2
10/27/2023 Red-Black Trees 6
A sequence of insertions into a red-black tree
• Every path from any node to all its leaf nodes has the same number of
black nodes.
• Otherwise, remove it and call the tree-fix algorithm on y’s child x (the
node which replaced the position of y)
• x has a black token and is colored red, so just color it black and
remove token a we are done!
Colors of y and z
were swapped
Remarks:
• the roots of subtrees C and D
are black
Right_rotate(y) Colors of x and y
• the second is the symmetric were swapped
case, when x is the right
child
10/27/2023 Red-Black Trees 11
Tree Fix algorithm cases: case (3)
x’s sibling is black and both nephews are black
Remarks:
• nephews are roots of subtrees C and D
• the black token is passed one level up
Colors of z and y
Left_rotate(x) Right_rotate(z) were swapped.
Far nephew is
colored black and
black token is removed.
Colors of x and y
were swapped
10/27/2023 Red-Black Trees 13
A sequence of removals from a red-black tree
after restructuring
removal of 12, causing a double black
(handled by restructuring)
10/27/2023 Red-Black Trees 14
Red-Black Trees efficiency
• Let n be the number of nodes.
• All operations work in time O(log n)! – much more efficient than
linked list or arrays implementation of sorted list!
• self-balancing
• Efficient
• Simple structure