Balanced Trees (AVL, Red-Black, B-Trees)
How self-balancing trees guarantee O(log n) with rotations — and why databases use B-trees instead.
A plain BST can degrade to height n. Self-balancing BSTs perform small local restructurings — rotations — on every insert and delete to keep the height O(log n), guaranteeing O(log n) operations in the worst case.
Rotations: the basic move
A rotation changes the tree's shape while preserving BST order. A right rotation at y lifts its left child x up:
TreeNode rotateRight(TreeNode y) {
TreeNode x = y.left;
y.left = x.right; // B moves under y
x.right = y;
return x; // new subtree root
}
TreeNode rotateLeft(TreeNode x) {
TreeNode y = x.right;
x.right = y.left;
y.left = x;
return y;
}def rotate_right(y):
x = y.left
y.left = x.right # B moves under y
x.right = y
return x # new subtree root
def rotate_left(x):
y = x.right
x.right = y.left
y.left = x
return yfunction rotateRight(y: TreeNode): TreeNode {
const x = y.left!;
y.left = x.right; // B moves under y
x.right = y;
return x;
}
function rotateLeft(x: TreeNode): TreeNode {
const y = x.right!;
x.right = y.left;
y.left = x;
return y;
}AVL trees
Every node stores its height and enforces a strict rule: the balance factor height(left) − height(right) is −1, 0 or +1. After an insert or delete, walk back up; at the first unbalanced node apply one of four fixes:
| Case | Shape | Fix |
|---|---|---|
| Left-Left | Heavy left child, heavy on its left | Rotate right |
| Right-Right | Mirror image | Rotate left |
| Left-Right | Heavy left child, heavy on its right | Rotate child left, then node right |
| Right-Left | Mirror image | Rotate child right, then node left |
AVL trees are strictly balanced (height ≤ ~1.44 log₂ n), so lookups are slightly faster, but writes rotate more often.
Red-black trees
Each node is red or black, with these invariants:
- The root is black; null leaves count as black.
- A red node never has a red child.
- Every path from a node down to null leaves contains the same number of black nodes.
Together these guarantee the longest path is at most twice the shortest, so height ≤ 2 log₂(n+1). Fixing a violation needs at most 2 rotations per insert and 3 per delete (plus recolouring), making writes cheaper than AVL.
Red-black trees power Java's TreeMap/TreeSet, C++ std::map/std::set, the Linux kernel's scheduler and memory-area tracking, and treeified HashMap buckets.
- Height ≤ 1.44 log n (tighter)
- Faster lookups
- More rotations on write
- Good for read-heavy data
- Height ≤ 2 log n
- O(1) rotations per update
- Standard-library default
- Good general-purpose choice
B-trees and B+ trees: balanced trees for disks
On disk, the cost that matters is how many blocks you read, not comparisons. A B-tree of order m stores up to m−1 keys and m children per node, sized to fill a disk page (4–16 KB → hundreds of keys). The tree is extremely shallow: with 500 keys per node, 3 levels hold 125 million keys.
A B+ tree — used by virtually every relational database and many file systems — keeps all values in the leaves, links the leaves into a list for fast range scans, and uses internal nodes only for routing. Details in Database indexing.
| Structure | Balance guarantee | Used for |
|---|---|---|
| AVL | balance factor within ±1 | Read-heavy in-memory maps |
| Red-black | Equal black-height | Standard libraries, kernels |
| B-tree / B+ tree | All leaves at the same depth | Databases, file systems |
| Skip list | Probabilistic | Redis sorted sets, LSM memtables |
| Treap / splay tree | Randomised / amortized | Competitive programming, caches |
- Rotations restructure locally in O(1) while preserving BST order.
- AVL: strict balance, faster reads. Red-black: looser balance, cheaper writes, the library default.
- B/B+ trees maximise keys per node to minimise disk reads; they are the index structure of databases.
- You rarely implement these yourself — but you must know their guarantees.
QWhy do databases use B+ trees rather than red-black trees?medium
Storage I/O happens in pages. A B+ tree node fills a page with hundreds of keys, so height stays around 3–4 even for billions of rows, minimising page reads. Linked leaves make range scans sequential. A binary tree would need about 30 random page reads per lookup.
QWhat's the time complexity of TreeMap operations and why?easy
O(log n) for get/put/remove/floorKey/ceilingKey because it's a red-black tree with height ≤ 2 log₂(n+1). Iteration is O(n) in sorted order.
QCheck whether a binary tree is height-balanced.easy
Post-order recursion returning the height, or −1 if any subtree is unbalanced (height difference > 1). O(n) — avoid recomputing heights at every node, which costs O(n log n) to O(n²).