Balanced Trees (AVL, Red-Black, B-Trees)

How self-balancing trees guarantee O(log n) with rotations — and why databases use B-trees instead.

Advanced 4 min readLesson 9 of 16 Interview Q&A

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:

yxCABxAyBCrotateRight(y)
Order A < x < B < y < C is preserved; only subtree B changes parent. O(1) pointer updates.
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;
}

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:

CaseShapeFix
Left-LeftHeavy left child, heavy on its leftRotate right
Right-RightMirror imageRotate left
Left-RightHeavy left child, heavy on its rightRotate child left, then node right
Right-LeftMirror imageRotate 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:

  1. The root is black; null leaves count as black.
  2. A red node never has a red child.
  3. 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.

AVL
  • Height ≤ 1.44 log n (tighter)
  • Faster lookups
  • More rotations on write
  • Good for read-heavy data
Red-Black
  • 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.

[ 30 | 60 ][ 5 | 12 | 21 ][ 35 | 41 | 52 ][ 70 | 85 | 99 ]
A B-tree node holds many sorted keys; each child covers the range between two 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.

StructureBalance guaranteeUsed for
AVLbalance factor within ±1Read-heavy in-memory maps
Red-blackEqual black-heightStandard libraries, kernels
B-tree / B+ treeAll leaves at the same depthDatabases, file systems
Skip listProbabilisticRedis sorted sets, LSM memtables
Treap / splay treeRandomised / amortizedCompetitive programming, caches
Key takeaways
  • 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.
Interview questions
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²).