Red-Black Trees




CS146

Chris Pollett

Apr 14, 2014

Outline

Introduction

How to Randomly Build a Tree

Self-Balancing Trees

Red-Black Trees

Definition. A red-black tree is a binary search tree where each node also has color which can be either red or black and where the nodes of the tree satisfy the following red-black properties:
  1. Every node is either red or black.
  2. The root is black.
  3. Every leaf (NIL) is black.
  4. If a node is red, then both its children are black. (a little like fullness)
  5. For each node, all simple paths from the node to descendant leaves contains the same number of black nodes. (a little like comparing left and right heights)

Example Red-Black Tree

An Example Red Black Tree

Quiz (Sec 5)

Which of the following statements is true?

  1. The multiple array representation of an object uses less memory than the single array representation of an object.
  2. The TRANSPLANT procedure we described last day for binary trees was `Omega(log n)`.
  3. The TREE-INSERT procedure we described last day made use of a trailing pointer.

Quiz (Sec 6)

Which of the following statements is true?

  1. A free space list as described in the book is a singly linked list.
  2. TREE-SUCCESSOR(x) will always return a node in a subtree of `x`.
  3. In the worst case, TREE-DELETE(T,z) is a `O(log n)` algorithm.

Height of Red-Black Trees

The folowing lemma shows that red-black trees make good search trees:

Lemma. A red-black tree with `n` internal nodes has height at most `2log(n+1)`.

Proof. We claim first that the subtree rooted at any node `x` contains at least `2^(bh(x)) - 1` internal nodes. We prove this claim by induction on the height of `x`. If `x` has height `0`, then `x` must be a leaf, and the subtree rooted at `x` contains `2^(bh(x)) - 1 = 2^0 - 1 = 0` internal nodes. For the induction step, let `x` be a node of positive height and suppose it is an internal node with two children. A child will have black-height `bh(x)` if the child is red and `bh(x) - 1` if the child is black. Since the child of `x` has less height than `x`, we can apply the induction hypothesis to conclude that each child has at least `2^(bh(x) - 1) -1` internal nodes. So the subtree root at `x` had at least
`(2^(bh(x) -1) - 1) + (2^(bh(x) -1 ) - 1) + 1 = (2^(bh(x)) - 1)` internal nodes. So the induction hypothesis holds in this case.

To complete the proof of the lemma, let `h` be the height of the tree. By Property 4, at least half the nodes on any simple path from the root to a leaf, not including the root must be black. So the black height must be at least `h/2`. So `n ge 2^(h/2) -1`. Moving `1` to the right hand side and taking logarithms on both sides yields
`log(n+1) ge h/2` or `h le 2log(n + 1)`.

Rotations

Red Black Tree Rotations