Red-Black Trees

A Self-Balancing Binary Search Tree Data Structure

What is a Red-Black Tree?

A Red-Black Tree is a type of self-balancing binary search tree where each node has an extra bit to store its color (red or black). This data structure ensures that the tree remains approximately balanced during insertions and deletions, guaranteeing O(log n) time complexity for basic operations.

Red-Black Tree Properties

Every Red-Black Tree must satisfy these fundamental properties:

  1. Every node is either red or black
  2. The root node is always black
  3. All leaf nodes (NIL nodes) are black
  4. Red nodes cannot have red children (no two red nodes can be adjacent)
  5. Every path from a node to its descendant NIL nodes contains the same number of black nodes

Key Operations

Basic Operations

Balancing Operations

When the Red-Black properties are violated during insertion or deletion, the tree uses these operations to restore balance:

Visual Representation

Red-Black Tree Example Diagram

Example of a Red-Black Tree with red and black nodes

Advantages & Applications

Performance

Guaranteed O(log n) for search, insert, and delete operations

Balance

Self-balancing property prevents degeneration into a linear structure

Real-world Use

Used in Java's TreeMap, Linux kernel's CFS scheduler, and many databases