Order
Keys remain organized like any BST; in-order traversal is increasing.
Algorithms · Balanced data structures
A red-black tree is a binary search tree that limits imbalance through colors, recoloring and rotations. It is not perfectly balanced, but it guarantees logarithmic height.
A BST built from sorted keys can degenerate into a chain of height n. A red-black tree preserves the BST property and constrains colors along paths: no path can become more than twice as long as another.
Keys remain organized like any BST; in-order traversal is increasing.
Every node adds one logical bit: red or black.
After an update, recoloring and a constant number of rotations are enough.
Every node is either red or black.
The root is black.
Every NIL leaf—that is, every null pointer—is black.
A red node has black parent and children: two red nodes can never be consecutive.
Every path from a node to a descendant NIL contains the same number of black nodes: its black height.
Every new key enters red. Step through the trace to see which violation appears and how recoloring and rotations move or remove it.
BST-insert(z); z.color ← REDwhile color(parent(z)) = RED if color(uncle(z)) = RED: recolor and move z up else if z is an inner child: rotate parent(z) recolor parent and grandparent rotate grandparent(z)root.color ← BLACKParent and uncle become black, grandparent becomes red and z moves to the grandparent. The violation may propagate upward.
z is an inner child. Rotate its parent to turn the triangle into a line, reducing to the next case.
The parent becomes black, the grandparent red, and a rotation at the grandparent removes the red–red pair.
Right–left cases mirror left–right cases. The visualizer explicitly names the chosen direction.
Contract each red node into its black parent. The red–red rule lets each black node absorb at most two red children; black height makes every resulting path equally long. Therefore:
h ≤ 2 log₂(n + 1)
| Operation | Worst-case time | Note |
|---|---|---|
| Search | Θ(log n) | Follows one path. |
| Insertion | Θ(log n) | Search + fix-up; at most 2 rotations. |
| Deletion | Θ(log n) | Search + fix-up; at most 3 rotations. |
| Space per node | Θ(1) | Color and pointers. |
Deleting a red node does not change black height. Deleting a black node removes one black from paths through it, so the algorithm temporarily represents the deficit as “double black” and repairs it by inspecting sibling and nephews. There are more cases, but the tools are the same: recoloring and rotations.