CIS 3223. Data Structures and Algorithms
Self-balancing search trees (2)
1. Red-Black tree
Red-Black tree is another self-balancing binary search tree. It has the following
properties:
- A node is either red or black.
- The root is black.
- If a node is red, then its children are both black (an empty reference, null, is considered to refer to a black node).
- Every path from a node to a descendant leaf contains the same number of black nodes.
It follows from the above definition that in a Red-Black tree, no leaf is more
than twice as far from the root as any other, which gives another type of "balance".
A red-black tree with n internal nodes has height at most 2log(n+1).
11
/ \
2 14
/ \
1 7
/ \
5 8
2. Insertion
Similar to in AVL tree, an insertion in a Red-Black tree is an insertion in a
binary search tree, sometimes followed by a rotation to keep the balance.
The new node gets the color red. After the insertion, there are the following possibilities:
- If the parent of the new node is black, the operation ends.
- If the parent and its sibling are also red, the color of the parent, its sibling,
and the grandparent are all changed. If the grandparent is the root, it is changed
back to black.
- If the parent is red, but has no red sibling, do a rotation among the new node, its parent, and its grandparent, so that the node with a middle value of the three takes the previous position of the grandparent (in the same way as in an AVL tree),
and make it black and the other two red.
The above process may need to be repeated for the grandparent node, all the way up the tree.
Example: an
animation of insertion in a Red-Black tree.
3. Deletion
For deletion in a Red-Black tree, do binary search tree deletion first, then check
the balance. Since the node actually removed has one or no child, there are the
several possibilities. If the removed node is red, the process ends. However,
if the removed node is black, rotation and re-coloring may be necessary.
An
applet for insertion and deletion in a Red-Black tree.
Since deletion is complicated in Red-Black tree, sometimes the node is just
marked as "deleted", without being removed from the tree.
4. Implementation
In a Red-Black tree, the major operations take O(log N) time in the worst cases.
Compared to an AVL tree, it is a little more efficient, but less intuitive.
The Java
TreeMap class implements a Red-Black tree.