What is Red-Black tree in Data Structures?
A red-black tree is a self-balancing binary search tree in which every node is coloured either red or black. The colours are not decoration: a small set of colouring rules limits how unbalanced the tree can become, so its height always stays O(log n).
Each node stores one extra bit for its colour. After every insertion or deletion, the tree checks the rules and repairs any violation with recolouring and at most a few rotations.
The idea goes back to Rudolf Bayer's "symmetric binary B-trees" (1972); the red-black formulation and name were introduced by Leonidas Guibas and Robert Sedgewick in 1978.
Properties of Red Black Tree
It is a binary search tree: smaller keys to the left, larger keys to the right.
Every node is either RED or BLACK.
The root is BLACK.
Every leaf (the empty NIL/null child) is considered BLACK.
A RED node never has a RED child, so two red nodes are never adjacent on a path.
For every node, all paths from that node down to the NIL leaves below it contain the same number of BLACK nodes. This number is the node's black height.
Together, the last two rules mean the longest root-to-leaf path (alternating red and black) is at most twice as long as the shortest (all black), which bounds the height by about 2 log2(n + 1).
Example of a Red-Black Tree

The tree above satisfies every rule: the root is black, no red node has a red child, and every path from the root down to a NIL leaf passes through the same number of black nodes.
Why use a Red-Black tree in application development?
A red-black tree keeps data sorted and guarantees O(log n) search, insertion and deletion even in the worst case, whatever order the keys arrive in. It works with any key type that can be compared: numbers, strings, dates or your own objects with a Comparator.
That makes it a natural basis for ordered sets and maps. Java's TreeMap and TreeSet are red-black trees, and HashMap turns very long collision buckets into small red-black trees.
Operations on Red-Black Tree
A red-black tree supports the usual BST operations, plus rotations used internally to restore balance:
- Search: exactly as in a BST, O(log n).
- Insertion: insert as in a BST and colour the new node red; if its parent is also red, fix the tree by recolouring (when the uncle is red) or by one or two rotations (when the uncle is black).
- Deletion: delete as in a BST; if a black node was removed, one path lost a black node, and the repair uses recolouring and at most three rotations.
- Rotation: a local restructuring (left or right) that changes the shape of the tree without breaking the BST order.
Implement a Red-Black Tree in Java
The program below implements insertion, deletion and search. It uses a single black sentinel node, NIL, in place of every empty child, which removes many null checks from the repair code. The comments name the classic repair cases (three for insertion, four for deletion, each with a mirror image).
// A red-black tree of int keys with insert, delete, search and printing.
// It follows the classic algorithm with a shared black sentinel node (NIL)
// that stands for every empty child and for the root's parent.
public class RedBlackTree {
private static final boolean RED = true;
private static final boolean BLACK = false;
private static class Node {
int key;
boolean color;
Node left, right, parent;
Node(int key, boolean color) {
this.key = key;
this.color = color;
}
}
private final Node NIL = new Node(0, BLACK); // sentinel: always black
private Node root = NIL;
// ---------- search ----------
public boolean contains(int key) {
return find(key) != NIL;
}
private Node find(int key) {
Node x = root;
while (x != NIL && key != x.key) {
x = (key < x.key) ? x.left : x.right;
}
return x;
}
// ---------- rotations ----------
// x's right child y moves up; x becomes y's left child
private void rotateLeft(Node x) {
Node y = x.right;
x.right = y.left;
if (y.left != NIL) y.left.parent = x;
y.parent = x.parent;
if (x.parent == NIL) root = y;
else if (x == x.parent.left) x.parent.left = y;
else x.parent.right = y;
y.left = x;
x.parent = y;
}
// mirror image of rotateLeft
private void rotateRight(Node x) {
Node y = x.left;
x.left = y.right;
if (y.right != NIL) y.right.parent = x;
y.parent = x.parent;
if (x.parent == NIL) root = y;
else if (x == x.parent.right) x.parent.right = y;
else x.parent.left = y;
y.right = x;
x.parent = y;
}
// ---------- insertion ----------
public void insert(int key) {
Node z = new Node(key, RED); // new nodes start red
z.left = z.right = NIL;
Node parent = NIL;
Node x = root;
while (x != NIL) { // ordinary BST descent
parent = x;
if (key == x.key) return; // ignore duplicates
x = (key < x.key) ? x.left : x.right;
}
z.parent = parent;
if (parent == NIL) root = z;
else if (key < parent.key) parent.left = z;
else parent.right = z;
fixAfterInsert(z);
}
// Repairs a red node z whose parent may also be red
private void fixAfterInsert(Node z) {
while (z.parent.color == RED) {
Node grand = z.parent.parent;
if (z.parent == grand.left) {
Node uncle = grand.right;
if (uncle.color == RED) { // case 1: recolor and move up
z.parent.color = BLACK;
uncle.color = BLACK;
grand.color = RED;
z = grand;
} else {
if (z == z.parent.right) { // case 2: turn into case 3
z = z.parent;
rotateLeft(z);
}
z.parent.color = BLACK; // case 3: recolor and rotate
grand.color = RED;
rotateRight(grand);
}
} else { // same three cases, mirrored
Node uncle = grand.left;
if (uncle.color == RED) {
z.parent.color = BLACK;
uncle.color = BLACK;
grand.color = RED;
z = grand;
} else {
if (z == z.parent.left) {
z = z.parent;
rotateRight(z);
}
z.parent.color = BLACK;
grand.color = RED;
rotateLeft(grand);
}
}
}
root.color = BLACK;
}
// ---------- deletion ----------
// Puts subtree v in the place of subtree u
private void replace(Node u, Node v) {
if (u.parent == NIL) root = v;
else if (u == u.parent.left) u.parent.left = v;
else u.parent.right = v;
v.parent = u.parent;
}
private Node minimum(Node x) {
while (x.left != NIL) x = x.left;
return x;
}
public void delete(int key) {
Node z = find(key);
if (z == NIL) return; // key not present
Node y = z; // node actually removed or moved
boolean removedColor = y.color;
Node x; // node that takes y's place
if (z.left == NIL) {
x = z.right;
replace(z, z.right);
} else if (z.right == NIL) {
x = z.left;
replace(z, z.left);
} else {
y = minimum(z.right); // inorder successor
removedColor = y.color;
x = y.right;
if (y.parent == z) {
x.parent = y;
} else {
replace(y, y.right);
y.right = z.right;
y.right.parent = y;
}
replace(z, y);
y.left = z.left;
y.left.parent = y;
y.color = z.color;
}
if (removedColor == BLACK) { // a black node was lost on one path
fixAfterDelete(x);
}
}
// x carries an "extra black"; push it up or remove it with recoloring/rotations
private void fixAfterDelete(Node x) {
while (x != root && x.color == BLACK) {
if (x == x.parent.left) {
Node w = x.parent.right; // x's sibling
if (w.color == RED) { // case 1: make the sibling black
w.color = BLACK;
x.parent.color = RED;
rotateLeft(x.parent);
w = x.parent.right;
}
if (w.left.color == BLACK && w.right.color == BLACK) {
w.color = RED; // case 2: move the extra black up
x = x.parent;
} else {
if (w.right.color == BLACK) { // case 3: turn into case 4
w.left.color = BLACK;
w.color = RED;
rotateRight(w);
w = x.parent.right;
}
w.color = x.parent.color; // case 4: fix and finish
x.parent.color = BLACK;
w.right.color = BLACK;
rotateLeft(x.parent);
x = root;
}
} else { // same four cases, mirrored
Node w = x.parent.left;
if (w.color == RED) {
w.color = BLACK;
x.parent.color = RED;
rotateRight(x.parent);
w = x.parent.left;
}
if (w.right.color == BLACK && w.left.color == BLACK) {
w.color = RED;
x = x.parent;
} else {
if (w.left.color == BLACK) {
w.right.color = BLACK;
w.color = RED;
rotateLeft(w);
w = x.parent.left;
}
w.color = x.parent.color;
x.parent.color = BLACK;
w.left.color = BLACK;
rotateRight(x.parent);
x = root;
}
}
}
x.color = BLACK;
}
// ---------- printing ----------
// Prints one node per line, indented by depth (L = left child, R = right child)
public void printTree() {
print(root, "", "root");
}
private void print(Node node, String indent, String label) {
if (node == NIL) return;
System.out.println(indent + label + ": " + node.key + (node.color == RED ? " (RED)" : " (BLACK)"));
print(node.left, indent + " ", "L");
print(node.right, indent + " ", "R");
}
public static void main(String[] args) {
RedBlackTree tree = new RedBlackTree();
int[] keys = {45, 60, 30, 70, 25, 50};
for (int key : keys) {
tree.insert(key);
}
System.out.println("Tree after inserting 45, 60, 30, 70, 25, 50:");
tree.printTree();
tree.delete(70);
System.out.println();
System.out.println("Tree after deleting 70:");
tree.printTree();
System.out.println();
System.out.println("Contains 50? " + tree.contains(50));
System.out.println("Contains 70? " + tree.contains(70));
}
}
Tree after inserting 45, 60, 30, 70, 25, 50:
root: 45 (BLACK)
L: 30 (BLACK)
L: 25 (RED)
R: 60 (BLACK)
L: 50 (RED)
R: 70 (RED)
Tree after deleting 70:
root: 45 (BLACK)
L: 30 (BLACK)
L: 25 (RED)
R: 60 (BLACK)
L: 50 (RED)
Contains 50? true
Contains 70? falseAfter the six insertions the root 45 is black, its children 30 and 60 are black, and 25, 50 and 70 are red, so every path from the root has two black nodes. Deleting the red leaf 70 removes no black node, so no repair is needed.
Advantages of Red-Black Trees
- Guaranteed O(log n) search, insertion and deletion in the worst case.
- Few rotations per update (at most two for an insertion and three for a deletion), so frequent changes are cheap.
- Keeps keys in sorted order, so ordered traversal, minimum/maximum and range queries are easy.
- Predictable performance, which suits libraries and systems code (for example Java's
TreeMapandTreeSet).
Disadvantages of Red-Black Trees
- Complex to implement correctly, especially deletion.
- Each update pays for recolouring and possible rotations.
- For plain lookups without ordering, a hash table (O(1) on average) is faster.
- Less strictly balanced than an AVL tree, so searches can take slightly more steps.
- Each node stores a colour and usually a parent reference in addition to its key and children.
When to Use Red-Black Trees
A red-black tree is a good choice when:
- you need a sorted collection with guaranteed O(log n) operations;
- the data changes often, with frequent insertions and deletions, for example:
- ordered maps and sets in language libraries (Java
TreeMap, C++std::map); - in-memory indexes and schedulers that must always find the smallest or next key quickly;
- real-time systems where worst-case time matters more than average time.
- ordered maps and sets in language libraries (Java
When to Avoid Red-Black Trees
Another structure is usually better when:
- you only need fast lookups by key and no ordering: use a hash table;
- the data is searched far more often than it changes: an AVL tree's stricter balance gives slightly faster lookups;
- the data lives on disk: databases use B-trees and B+ trees, which read many keys per disk access;
- the collection is small or rarely changes: a sorted array with binary search is simpler.
Red-Black Vs AVL Tree
| Feature | Red-Black Tree | AVL Tree |
|---|---|---|
| Balance rule | Colour rules; height at most about 2 log2(n + 1) | Subtree heights differ by at most 1; height at most about 1.44 log2 n |
| Insertion/Deletion | Fewer rotations (at most 2 for insert, 3 for delete) | More rotations; deletion may rotate at every level |
| Searching | O(log n), slightly more steps on average | O(log n), slightly fewer steps |
| Extra data per node | One colour bit | A height or balance factor (-1, 0 or +1) |
| Best for | Update-heavy workloads, general-purpose libraries | Lookup-heavy workloads |
In Summary
A red-black tree is a binary search tree with a colour bit per node and a few simple rules that keep its height logarithmic. It trades a little search speed, compared with an AVL tree, for cheaper updates, which is why it is the default ordered-map structure in many standard libraries. For unordered lookups use a hash table, and for disk-based data use a B-tree or B+ tree.