Browse curriculum

Red-Black Tree

A self-balancing binary search tree where each node is colored red or black, ensuring the tree remains approximately balanced during insertions and deletions.

READY

 

Insert values to watch the fix-up. A new node is always red; the rules then recolour and rotate until no red node has a red parent.

 

Value

Intuition

Standard BSTs can degrade into linked lists (O(n)) with sorted input. AVL trees are strictly balanced but require frequent rotations. Red-Black trees trade some balance for faster insertion/deletion (fewer rotations), guaranteeing O(log n) operations while maintaining a height at most 2 * log(n+1).

Concept

A Red-Black Tree is a BST with 5 properties:

  1. Nodes are Red or Black.
  2. Root is always Black.
  3. Leaves (NIL) are Black.
  4. If a node is Red, both children are Black (no double reds).
  5. Every path from a node to its descendant NIL nodes has the same number of Black nodes.

How it Works

  • Insertion: Insert like BST (red node). Fix violations (recoloring or rotation) if parent is also red.
  • Deletion: Complex. If a black node is deleted, tree height reduces, violating black-height. Requires restructuring.
  • Rotations: Left and Right rotations are used to rebalance.
  • Recoloring: Changing node colors to fix parent-child conflicts.

Step-by-Step Breakdown

Insertion Logic:
  1. Insert node as RED.
  2. If parent is Black: Done.
  3. If parent is Red: Check uncle's color.
  4. Uncle Red: Recolor Parent+Uncle Black, Grandparent Red. Repeat for GP.
  5. Uncle Black: Rotate (LL, RR, LR, RL cases) and recolor.

When to Use

  • General purpose self-balancing tree (used in C++ std::map, Java TreeMap).
  • When insertions/deletions are frequent (faster than AVL).
  • Implementing associative arrays.

When NOT to Use

  • When lookups are the dominant operation (AVL is strictly balanced, so slightly faster lookups).
  • Simple scenarios where O(n) is acceptable.

How to Identify

Keywords: "Map Implementation", "Self-Balancing", "Associative Array", "Ordered Set".

Applying for software engineering roles? Free, no sign-up:

AI resume checker — match your resume to the job description

Frequently Asked Questions

What are Red-Black properties?

Every node is either red or black, the root is black, no two red nodes are adjacent, and every path from a node to descendant leaves contains the same number of black nodes.


Red-Black vs AVL Trees?

AVL trees are more strictly balanced but require more rotations. Red-Black trees are more efficient for frequent insertions and deletions.


Commercial uses of Red-Black Trees?

They are used in many production libraries: C++ STL (std::map, std::set), Java TreeMap, and Linux kernel process scheduling.