A Red-Black Tree is a self-balancing binary search tree (BST) that guarantees O(log n) time for search, insert, and delete operations. It is the underlying data structure for Java's TreeMap
and TreeSet
.
A Binary Search Tree is a tree data structure where each node has at most two children, and for every node:
BSTs allow fast lookup, insertion, and deletion, but can become unbalanced, leading to poor performance (O(n) in the worst case).
// Simple BST Node in Java
class Node {
int value;
Node left, right;
Node(int value) {
this.value = value;
}
}
A Red-Black Tree is a special kind of BST with extra properties to ensure the tree remains balanced:
These properties guarantee that the longest path from the root to a leaf is no more than twice as long as the shortest path, ensuring O(log n) operations.
// Red-Black Tree Node (conceptual)
class RBNode {
int value;
RBNode left, right;
boolean isRed;
RBNode(int value) {
this.value = value;
this.isRed = true; // new nodes are red by default
}
}
Pro Tip: Red-Black Trees are more efficient for frequent insertions and deletions compared to AVL trees, which are stricter in balancing.
Java's TreeMap
and TreeSet
use a Red-Black Tree under the hood. This ensures that all operations (get, put, remove, etc.) are O(log n).
// Example: Using TreeMap in Java
import java.util.TreeMap;
public class RBTreeMapDemo {
public static void main(String[] args) {
TreeMap map = new TreeMap<>();
map.put(10, "Ten");
map.put(20, "Twenty");
map.put(15, "Fifteen");
System.out.println(map);
}
}
Note: TreeMap maintains keys in sorted order and provides efficient range queries.
TreeMap
when you need sorted keys and efficient range queries.HashMap
(O(1) average) and TreeMap
(O(log n)).Collections.synchronizedSortedMap
or external synchronization for thread safety.
Red-Black Trees are a foundational data structure for efficient, balanced maps and sets in Java. Understanding their properties and how TreeMap uses them will help you write more efficient and reliable code.