Balanced search trees
Binary search trees that rebalance themselves with rotations, guaranteeing O(log n) search, insert and delete whatever order keys arrive in.
Description
A plain binary search tree is only fast when it's bushy. Insert keys in sorted order and it degrades into a chain. Balanced search trees fix this by checking their shape after each insert or delete and repairing it with rotations: local rearrangements that keep the left-smaller, right-larger order but change which node sits higher.
An AVL tree keeps the heights of every node's two subtrees within one of each other. It's strictly balanced, so lookups are as fast as possible, at the cost of more rotations on writes.
A red-black tree colors nodes red or black and enforces rules that keep the longest path at most twice the shortest. It's a little less balanced but needs fewer rotations, so it's popular for general-purpose ordered maps: Java's TreeMap, C++'s std::map and the Linux kernel's scheduler use red-black trees.
B-trees generalize the idea to nodes with many keys and children, so that a tree of millions of keys is only three or four levels deep. That suits disks and SSDs, where reading one large node costs about the same as reading a small one: almost every relational database index is a B-tree (or its B+ tree variant).
How it works
Keys 10–70 inserted in order into a plain BST: a chain of height 7
- 10 → 20
- 20 → 30
- 30 → 40
- 40 → 50
- 50 → 60
- 60 → 70
- 70
The same keys in a balanced tree: height 3
- 40 → 20, 60
- 20 → 10, 30
- 60 → 50, 70
- 10
- 30
- 50
- 70
Complexity
| Operation | Average | Worst |
|---|---|---|
| Search | O(log n) | O(log n) |
| InsertIncluding any rotations. | O(log n) | O(log n) |
| Delete | O(log n) | O(log n) |
| Range query (k results) | O(log n + k) | O(log n + k) |
| Ordered traversal | O(n) | O(n) |
Space: O(n)
AVL trees have height at most about 1.44 log₂ n; red-black trees at most 2 log₂ n. B-trees with hundreds of keys per node keep even billions of keys within a handful of levels.
TypeScript implementation
An AVL tree with rotations on insert, compared with a plain BST on the same sorted input.
// An AVL tree: after each insert, nodes whose subtrees differ in height by
// more than one are fixed with a single or double rotation.
class AvlNode {
key: number;
height = 1;
left: AvlNode | null = null;
right: AvlNode | null = null;
constructor(key: number) {
this.key = key;
}
}
const h = (n: AvlNode | null) => (n ? n.height : 0);
const update = (n: AvlNode) => (n.height = 1 + Math.max(h(n.left), h(n.right)));
const balance = (n: AvlNode) => h(n.left) - h(n.right);
function rotateRight(y: AvlNode): AvlNode {
const x = y.left!;
y.left = x.right;
x.right = y;
update(y);
update(x);
return x;
}
function rotateLeft(x: AvlNode): AvlNode {
const y = x.right!;
x.right = y.left;
y.left = x;
update(x);
update(y);
return y;
}
export class AvlTree {
root: AvlNode | null = null;
rotations = 0;
insert(key: number): void {
this.root = this.insertAt(this.root, key);
}
private insertAt(node: AvlNode | null, key: number): AvlNode {
if (!node) return new AvlNode(key);
if (key < node.key) node.left = this.insertAt(node.left, key);
else node.right = this.insertAt(node.right, key);
update(node);
const b = balance(node);
if (b > 1 && key < node.left!.key) return this.rot(() => rotateRight(node)); // left-left
if (b < -1 && key >= node.right!.key) return this.rot(() => rotateLeft(node)); // right-right
if (b > 1) {
node.left = rotateLeft(node.left!); // left-right
return this.rot(() => rotateRight(node));
}
if (b < -1) {
node.right = rotateRight(node.right!); // right-left
return this.rot(() => rotateLeft(node));
}
return node;
}
private rot(f: () => AvlNode): AvlNode {
this.rotations++;
return f();
}
get height(): number {
return h(this.root);
}
inOrder(n = this.root, out: number[] = []): number[] {
if (n) {
this.inOrder(n.left, out);
out.push(n.key);
this.inOrder(n.right, out);
}
return out;
}
}
export function demo(): string[] {
const small = new AvlTree();
for (const k of [10, 20, 30, 40, 50, 60, 70]) small.insert(k);
const big = new AvlTree();
for (let k = 1; k <= 1_000_000; k++) big.insert(k); // the worst case for a plain BST
return [
`10..70 inserted in order: height ${small.height}, root ${small.root!.key}, in-order ${small.inOrder().join(", ")}`,
`1 000 000 sorted inserts: height ${big.height} (a plain BST would be 1 000 000), ${big.rotations.toLocaleString("en")} rotations`,
];
}When to use it
Use it when
- You need an ordered map or set with guaranteed performance: ordered iteration, ranges, nearest keys.
- Keys may arrive in any order, including sorted.
- Implementing indexes, schedulers, interval and event queues.
Avoid it when
- Order doesn't matter: a hash table is faster on average.
- You can use a library: write your own balanced tree only to learn. Use the language's ordered map, or a sorted container library.
- The data is static: a sorted array is more compact and as fast to search.
Pitfalls
- Implementing deletion yourself: it's where most hand-written AVL and red-black trees go wrong.
- Forgetting to update heights or colors after rotations.
- Using a tree when a hash map would do: ordered structures are slower for plain lookups.
Alternatives
Hash table
Choose it when you don't need order.
Skip list
Choose it when you want an ordered structure that's simpler to make concurrent, as in Redis sorted sets.
B-tree or LSM tree
Choose it when the data lives on disk, as in databases.