Professional Documents
Culture Documents
2
6
1 4
7 1
1 2 3 4
4 1 0 7
1 1 1 2 2 3
0 6 9 3 8 8
1 1 2 3 3
7
2 5 0 5 9
Figure (a): A red-black tree with black nodes darkened and red nodes
shaded. Every node in a red-black tree is either red or black, the
children of the red nodes are both black, or every simple path from a
node to a descendant leaf contains the same number of black nodes.
Sentinel Nodes
Figure (b) shows another example of a red-black tree. As a matter of
convenience in dealing with boundary conditions in red-black tree
code, we use a single sentinel to represent NIL (the NULL contained
by leaf node). This sentinel node shows that we have reached to leaf.
For a red-black tree T, the sentinel nil[T ] is an object with the same
fields as an ordinary node in the tree. Its color field is BLACK, and its
other fields—p, left, right, and key—can be set to arbitrary values.
We use the sentinel so that we can treat a NIL child of a node x as an
ordinary node whose parent is x. Although we instead could add a
distinct sentinel node for each NIL in the tree, so that the parent of
each NIL is well defined, that approach would waste space. Instead,
we use the one sentinel nil[T ] to represent all the NIL’s—all leaves
and the root’s parent. As Figure (c) shows, all pointers to NIL are
replaced by pointers to the sentinel nil[T ]. The value of the fields p,
left, right, and key of the sentinel are immaterial, although we may
set them during the course of a procedure for our convenience.
Black Height
We call the number of black nodes on any path from, but not
including, a node x down to a leaf the black-height of the node,
denoted bh(x). By property 5, the notion of black-height is well
defined, since all descending paths from the node have the same
number of black nodes. We define the black-height of a red-black tree
to be the black-height of its root. For example in Figure (b), every
internal node is marked with black-height; NIL’s have black-height 0.
Lemma
A red-black tree with n internal nodes has height at most 2 log(n + 1).
2
3 6
1 4
3 2
7 1
1 2 2 3 4
2 2 1
4 1 0 7
1 1 1 1 2 2 3 N N
2 1 1 1 1
0 6 9 3 8 8
1 N N
N 1 1
1 1 1 N 2 3 3
7 1 N 1
2 5 0 N 5 9
N N N N N N N
1 3 N N
2 N N
6
N N
1 4
7 1
1 1 1 2 2 3
0 6 9 3 8 8
1 1 2 3 3
7
2 5 0 5 9
nil[T]
Figure (c): The same red-black tree but with each NIL replaced by
the single sentinel nil[T ], which is always black, and with black-
heights omitted. The root’s parent is also the sentinel.