Chapter 10 · Simulation

Red-Black Tree Simulator

← Chapter 10

Sample red-black tree loaded. Choose an operation.

Nodes0
Levels0
Black height0
Rotations0

Path

—

Rebalancing steps

  1. No rebalancing steps yet.

Red-Black Tree Simulator

A red-black tree is a self-balancing binary search tree. Every node is red or black, and empty (NIL) children count as black leaves. After an insertion or deletion, recoloring and rotations restore the properties below, which keeps the height O(log n).

How to use

  • Type an integer and press Insert, Search or Delete. The path is highlighted, and every recoloring and rotation appears under the rebalancing steps.
  • Validate checks the BST order and every red-black property.
  • Load example, Random tree and Reset replace the tree; Stop interrupts a running animation.

Red-black properties

  • Black root: the root is always black.
  • No red-red: a red node never has a red child.
  • Equal black height: every path from a node down to a NIL leaf passes through the same number of black nodes.

Insertion fix-up

A new node is inserted red. If its parent is red too, we look at the uncle (the parent's sibling):

  • Red uncle: color the parent and uncle black and the grandparent red, then continue the check from the grandparent.
  • Black uncle, triangle: a rotation at the parent turns the triangle into a straight line (the first half of a double rotation).
  • Black uncle, straight line: rotate at the grandparent; the parent becomes black and the grandparent red.
  • If the root ends up red, color it black.

Deletion fix-up

A node with two children is overwritten by its inorder successor. Removing a red node breaks nothing; removing a black node with a red child just turns that child black. Otherwise the node that takes its place becomes double black and is repaired according to its sibling:

CaseSiblingAction
Case 1RedRecolor, rotate at the parent; continue with Cases 2–4.
Case 2Black, both children blackColor the sibling red; the double black moves up.
Case 3Black, far child blackRotate at the sibling; continue with Case 4.
Case 4Black, far child redRecolor, rotate at the parent; the fix-up ends.