What’s it for?
We got a binary search tree, and we know that a binary search tree of height h can support any of the basic dynamic-set operations - such as Search, Predecessor – in O(h) time. The set operations are fast if the height of the search tree is small. So! If its height is large, the set operations may run no faster than a linked list.
What’s it?
Definition
Red-Black trees are one of many search-tree schemes that are “balanced” in order to guarantee that the basic dynamic-set operations take O(lgN) time in the worst case.
So, it’s a better binary search tree.
Basic Concept
Q: What’s kind of binary search tree is a Red-Black Tree?
- Every node is either red or black
- The root is black
- Every leaf is black
- If a node is red, then both its children are black
- For each node, all simple paths from the node to descendant leaves contains the same number of black nodes.
Black-Height: The number of black nodes on any simple path from, but not including, a node x down to a leaf.
Operations
Rotations
What’s it for?
The operations Insert and Delete modify the tree, the result may violate the red-black properties. We need to do something to restore these properties.
What’s it?
It’s a local operation in a search tree that preserves the binary-search-tree property.
Operations
We show two kinds of rotations here: Left-Rotate and Right-Rotate.

The above two node states are converted by Left-Rotation and Right-Rotation.
Precedes
- Left-Rotate
1 | y = x.right |
Insert
Process
In order to insert a new node into a Red-Black Tree in O(lgN) time, we do like this.
- Insert node Z into the tree T as if it were an ordinary binary search tree
- Color Z red
- Fix
Precedes
1 | RB-INSERT(T, z) |
This is what the simple Insertion do above.
1 | RB-INSERT-FIXUP(T, z) |
Now let’s take a look at the complete code:
1 |
|