Data Structures · Visualization
Red-Black Tree: Introduction
Red-Black Tree
A red-black tree is another type of self-balancing binary search tree. Time: O(log n) guaranteed for search, insert, and delete. Space: O(n).
Big-O: Operations O(log n); height ≤ 2·log₂(n+1).
Red-Black Tree: Introduction
Red-Black TreeA red-black tree is another type of self-balancing binary search tree. Instead of strictly tracking heights like an AVL tree, it colors each node either red or black and follows a small set of rules about how those colors can be arranged (e.g. a red node can't have a red child, and every path from root to an empty spot must pass through the same number of black nodes). These rules mathematically guarantee the tree never becomes more than roughly twice as deep as the ideal balanced height, keeping operations fast.
How Red-Black Tree: Introduction Works
- Follow all normal BST ordering rules (left is smaller, right is larger).
- Color every new node red when it's first inserted.
- Check the red-black rules: no red node has a red child, and every root-to-leaf path has the same number of black nodes.
- If a rule is broken, fix it using recoloring and/or rotations.
Red-Black Tree: Introduction Worked Example
Input: A small valid red-black tree
- Root is always colored black
- Root's children can be red, as long as they don't have red children themselves
- Every path from root down to an empty spot passes through the same count of black nodes
Output: A tree that stays roughly balanced without needing strict height tracking
Press ▶ Run to watch it step by step.
RED, BLACK = 0, 1
class RBNode:
def __init__(self, key, color=RED):
self.key = key
self.color = color
self.left = self.right = self.parent = None
# Five invariants:
# 1. Every node is red or black
# 2. The root is black
# 3. Every NIL leaf is black
# 4. A red node's children are both black
# 5. Every root -> NIL path has the same black count
# example: introRed-Black Tree: Introduction Time & Space Complexity
When to Use Red-Black Tree: Introduction
- Used internally in many language libraries (e.g. C++'s map/set, Java's TreeMap)
- Linux kernel's process scheduler and memory management structures
- Any system needing guaranteed O(log n) performance with slightly cheaper rebalancing than AVL trees
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Ready for the next step?
See the same ideas in action — visualize the algorithms that operate on these structures, or take a guided course.