Red-Black Trees
A Red-Black Tree (RBT) is a self-balancing binary search tree (BST) that ensures the tree remains approximately balanced after insertions and deletions. The primary goal of a Red-Black Tree is to keep the height of the tree O(log n), ensuring efficient operations.
Each node in a Red-Black Tree has an additional property: a color, which is either red or black. The tree follows specific rules regarding the colors, which ensures that it remains balanced.
Video Explanation

Red-Black Tree Visualizer
Below is an interactive Red-Black Tree visualizer. You can insert integer values to see how the tree automatically rebalances itself using left/right rotations and recoloring to satisfy the RBT properties.
Red-Black Tree Interactive Visualizer
Properties of Red-Black Trees
- Every node is either red or black.
- The root is always black.
- Every leaf (null node) is black.
- Red nodes cannot have red children (no two red nodes appear consecutively along a path).
- Every path from a node to its descendant leaves has the same number of black nodes.
These properties ensure that the longest path from the root to a leaf is no more than twice as long as the shortest path, guaranteeing O(log n) height.
Definition and Structure
A Red-Black Tree consists of nodes with the following attributes:
- Data: The value stored in the node.
- Left Child: A reference to the left subtree.
- Right Child: A reference to the right subtree.
- Color: Each node is either red or black, maintaining the Red-Black properties.
Types of Rotations
To maintain balance, Red-Black Trees utilize rotations similar to AVL Trees. These include:
- Left Rotation: Shifts the tree to the left when a right-heavy subtree becomes unbalanced.
- Right Rotation: Shifts the tree to the right when a left-heavy subtree becomes unbalanced.
- Left-Right Rotation: A left rotation followed by a right rotation, used when a left-heavy subtree's right child causes imbalance.
- Right-Left Rotation: A right rotation followed by a left rotation, used when a right-heavy subtree's left child causes imbalance.
Operations on Red-Black Trees
1. Insertion
Inserting a new node into a Red-Black Tree involves several steps:
- Insert the new node as you would in a regular BST.
- Color the new node red.
- Fix any violations of the Red-Black properties by adjusting the tree with recoloring and rotations.
Code Example (C++)
struct Node {
int data;
Node* left;
Node* right;
bool isRed;
};
Node* insert(Node* root, int key) {
// Insert like a regular BST node
if (root == nullptr) {
Node* newNode = new Node();
newNode->data = key;
newNode->left = nullptr;
newNode->right = nullptr;
newNode->isRed = true; // New nodes are always red
return newNode;
}
if (key < root->data)
root->left = insert(root->left, key);
else if (key > root->data)
root->right = insert(root->right, key);
// Fix Red-Black properties
return balance(root);
}