4.3. Red-Black Trees

This section discusses a type of balanced binary search trees called Red-Black Trees.

Red-Black trees preserve the balance at most time by satisfying the following conditions:

  • Every node is either red or black.

  • The root and all leaves (null) are black.

  • Every red node must have two black children.

  • Every path from a given node to any of its leaves goes through the same number of black nodes.

Red-Black Node

Let us create the RedBlackNode class inheriting AbstractBinaryNode:

  • L2: if is_red is true, the color of this node is red; otherwise, it is black.

  • L6: the color of the node is black by default upon instantiation.

Let us the RedBlackTree class inheriting AbstractBalancedBinarySearchTree:

Finally, let us override balance() method that handles 3 cases:

  • L3: sets the color to black if node is the root.

  • L5: if the color of node's parent is red:

    • L8: checks if the color of node's uncle is also red.

    • L10: the color of node's uncle is black.

What about the case when the color of node's parent is black?

The following shows a method that handles when both the parent and the uncle are red:

Are there any structural changes after this method is called?

The following shows a method that handles when the parent is red but the uncle is black:

  • L7: the case of left zig-zag.

  • L11: the case of right zig-zag.

  • L19: the case of left linear.

  • L21: the case of right linear.

The followings demonstrate how the balance() method works in Red-Black trees:

How does a Red-Black tree know when it is unbalanced?

Last updated

Was this helpful?