Simple Algorithm
Algorithms & Data Structures · Optimized · 24 min

Balanced Trees: AVL, Red-Black & B-Trees

Rotations and invariants that guarantee O(log n) height.

A plain BST is only as good as its insertion order, and real data arrives sorted all the time. Balanced trees refuse to rely on luck. They keep an invariant (sibling subtrees within one level of each other, or the same number of black nodes on every path) and repair it with rotations after each update. The reward is a worst-case guarantee: height O(log⁡n)O(\log n) on every input, so a million keys never cost more than a few dozen comparisons.

What you’ll learn

  • Prove that a rotation preserves the BST property, takes O(1)O(1) time and changes depths only locally.
  • Derive the AVL height bound h<1.4405log⁡2(n+2)−1.3277h<1.4405\log_2(n+2)-1.3277 from Fibonacci trees, and rebalance an AVL tree with the four rotation cases.
  • State the red-black properties, prove h≤2log⁡2(n+1)h\le2\log_2(n+1), and compare AVL and red-black trees by height and by rotations per update.
  • Explain why databases use B-trees and B+ trees, and choose between the library's ordered map, a hash map, a heap and a hand-written balanced tree.

Rotations: the one move

A balanced tree fights back against bad insertion orders with one local move, the rotation, applied after each update to restore an invariant that caps the height at O(log⁡n)O(\log n) in the worst case. Rotating right at yy lifts its left child xx: xx's right subtree β\beta becomes yy's left subtree, and yy becomes xx's right child. Rotating left at xx undoes it. Only three child pointers change, so a rotation takes O(1)O(1) time.

((α x β) y γ)  ⇄right at yleft at x  (α x (β y γ))\big((\alpha\ x\ \beta)\ y\ \gamma\big)\ \ \underset{\text{left at }x}{\overset{\text{right at }y}{\rightleftarrows}}\ \ \big(\alpha\ x\ (\beta\ y\ \gamma)\big)
Here (L v R)(L\ v\ R) is node vv with subtrees LL and RR. Both sides list α,x,β,y,γ\alpha,x,\beta,y,\gamma in inorder.
Think first In a right rotation at yy, which of the subtrees α\alpha, β\beta, γ\gamma changes its parent?

Only β\beta, which moves from xx (as its right subtree) to yy (as its left subtree). α\alpha stays under xx and γ\gamma under yy. The three child pointers that change are xx's right, yy's left, and the pointer from yy's old parent, which now points to xx.

AVL trees: siblings within one level

DerivationHow tall can an AVL tree be?
  1. N(h)=1+N(h−1)+N(h−2),N(0)=1,N(1)=2N(h)=1+N(h-1)+N(h-2),\qquad N(0)=1,\quad N(1)=2

    Let N(h)N(h) be the fewest nodes in an AVL tree of height hh. A smallest one has subtrees of heights h−1h-1 and h−2h-2, each as small as possible:

  2. N(h)+1=(N(h−1)+1)+(N(h−2)+1) ⟹ N(h)=Fh+3−1:  1, 2, 4, 7, 12, 20, 33,…N(h)+1=\big(N(h-1)+1\big)+\big(N(h-2)+1\big)\ \Longrightarrow\ N(h)=F_{h+3}-1:\ \ 1,\,2,\,4,\,7,\,12,\,20,\,33,\dots

    Adding 1 to both sides gives the Fibonacci recurrence, so with F1=F2=1F_1=F_2=1:

  3. h < log⁡φ ⁣(5 (n+2))−3h\ <\ \log_\varphi\!\big(\sqrt5\,(n+2)\big)-3

    With φ=(1+5)/2\varphi=(1+\sqrt5)/2, the golden ratio, Fk>φk/5−1F_k>\varphi^k/\sqrt5-1. An AVL tree with nn nodes and height hh therefore has n≥N(h)>φh+3/5−2n\ge N(h)>\varphi^{h+3}/\sqrt5-2:

  4. h < 1.4405log⁡2(n+2)−1.3277h\ <\ 1.4405\log_2(n+2)-1.3277

    In base 2, using 1/log⁡2φ=1.4404…1/\log_2\varphi=1.4404\ldots and log⁡φ5−3=−1.3277…\log_\varphi\sqrt5-3=-1.3277\ldots:

The trees that achieve N(h)N(h), called Fibonacci trees, are the tallest AVL trees of their size.

Insertion. Insert as in a plain BST, then walk back up updating heights. At the first ancestor zz whose balance factor reaches ±2\pm2, one of four configurations arises, named by the two steps from zz toward the new key. LL and RR are fixed by a single rotation at zz; LR and RL by a double rotation, first at zz's child, then at zz. The repaired subtree has exactly the height it had before the insertion, so nothing above zz changes: at most one single or double rotation per insertion.

Deletion. A repair can shorten the subtree, which may unbalance the next ancestor up, so a deletion may rotate at O(log⁡n)O(\log n) nodes on the way to the root; alternating insertions and deletions can even force Θ(log⁡n)\Theta(\log n) rotations per deletion again and again (Amani, Lai & Tarjan, 2015).

python
class Node:
    def __init__(self, key):
        self.key, self.left, self.right, self.h = key, None, None, 0

def h(x):   return x.h if x else -1            # height in edges; empty tree -1
def fix(x): x.h = 1 + max(h(x.left), h(x.right)); return x
def bf(x):  return h(x.left) - h(x.right)      # balance factor

def rotate_right(y):                           # y's left child x comes up
    x = y.left
    y.left, x.right = x.right, y
    fix(y); return fix(x)

def rotate_left(x):                            # x's right child y comes up
    y = x.right
    x.right, y.left = y.left, x
    fix(x); return fix(y)

def rebalance(x):
    fix(x)
    if bf(x) == 2:                             # left side too tall
        if bf(x.left) < 0: x.left = rotate_left(x.left)      # LR: double
        return rotate_right(x)                                # LL: single
    if bf(x) == -2:                            # right side too tall
        if bf(x.right) > 0: x.right = rotate_right(x.right)  # RL: double
        return rotate_left(x)                                 # RR: single
    return x

def insert(x, key):
    if x is None: return Node(key)
    if key < x.key:   x.left = insert(x.left, key)
    elif key > x.key: x.right = insert(x.right, key)
    return rebalance(x)

Recursive AVL insertion: rebalance runs at every ancestor on the way back up, but only the first unbalanced one rotates. Tested on random and sorted inputs, checking the balance factors and the inorder sequence; inserting 1,…,10231,\dots,1023 in order gives a perfect tree of height 9.

Think first Insert 10, 30, 20 into an empty AVL tree. Which repair happens?

At 10 the balance factor becomes −2-2, and the new key 20 lies to the right and then to the left of 10: the RL case. Rotate right at 30, then left at 10, and 20 becomes the root with children 10 and 30.

Predict before you look

What is the greatest possible height of an AVL tree with 10610^6 keys? (Heights count edges; a complete tree with 10610^6 keys has height 19.)

Show the answer

27

N(27)=F30−1=832,039≤106<N(28)=F31−1=1,346,268N(27)=F_{30}-1=832{,}039\le10^6<N(28)=F_{31}-1=1{,}346{,}268, so the tallest AVL tree with a million keys has height 27, about 1.44log⁡2n1.44\log_2 n, just under the bound 1.4405log⁡2(106+2)−1.3277≈27.41.4405\log_2(10^6+2)-1.3277\approx27.4. A red-black tree with a million keys can reach height 36, and a plain BST 999,999999{,}999.

Red-black trees: one bit of color

DerivationHeight at most 2 log₂(n + 1)
  1. #keys(x) ≥ 2(2bh(x)−1−1)+1 = 2bh(x)−1\#\text{keys}(x)\ \ge\ 2\big(2^{bh(x)-1}-1\big)+1\ =\ 2^{bh(x)}-1

    Black height. Let bh(x)bh(x) count the black nodes on any path from xx down to a NIL, the NIL included but not xx itself. By induction on the height of xx, its subtree holds at least 2bh(x)−12^{bh(x)}-1 keys, since each child has black height at least bh(x)−1bh(x)-1:

  2. bh(root) ≥ h′2  ⟹  n ≥ 2h′/2−1bh(\text{root})\ \ge\ \frac{h'}{2}\ \ \Longrightarrow\ \ n\ \ge\ 2^{h'/2}-1

    At least half black. Let h′h' be the number of edges on the longest path from the root down to a NIL. Red nodes are never adjacent and the NIL is black, so at least half of the h′h' nodes below the root on that path are black:

  3. h < h′ ≤ 2log⁡2(n+1)h\ <\ h'\ \le\ 2\log_2(n+1)

    Solve for h′h'. The height counted between keys, h=h′−1h=h'-1, is smaller still (CLRS, Lemma 13.1):

Insertion colors the new node red, which changes no black height, and repairs a red node with a red parent in one of three cases: if the new node's uncle is red, recolor and continue two levels up; otherwise one or two rotations finish the job. A red-black tree makes at most 2 rotations per insertion and at most 3 per deletion. Recoloring can climb O(log⁡n)O(\log n) levels in the worst case, but it is O(1)O(1) amortized (Tarjan, 1983). The cases, and why each one is a 2-3-4-tree operation in disguise, are the subject of the Optimal lesson Red-Black Trees & 2-3-4 Trees.

Think first Why is a newly inserted node colored red rather than black?

A black node would add one to the black count of every path through it, breaking rule 3 all the way up to the root. A red node changes no black count; it can only produce a red node with a red parent, a local violation that recoloring and rotations repair.

PropertyAVL treeRed-black tree
Invariant∣bf(x)∣≤1\abs{\text{bf}(x)}\le1 at every nodeNo red node has a red child; equal black counts on all paths
Height bound<1.4405log⁡2(n+2)−1.3277<1.4405\log_2(n+2)-1.3277≤2log⁡2(n+1)\le2\log_2(n+1)
Tallest with n=106n=10^62736
Rotations per insertionAt most one single or doubleAt most 2
Rotations per deletionO(log⁡n)O(\log n)At most 3
Extra data per nodeA height or a balance factor (2 bits)1 color bit
Typical useLookup-heavy workloadsstd::map and std::set (libstdc++, libc++, MSVC), Java's TreeMap, the Linux kernel's rbtree
AVL trees are shorter, so searches are a little faster; red-black trees restructure less, so updates are a little cheaper. Both guarantee O(log⁡n)O(\log n) for everything.

B-trees: wide nodes for slow memory

Everything so far counts comparisons. On disk, and even in RAM, that is the wrong cost: an SSD reads a block of several kilobytes at a time, and a CPU fetches 64-byte cache lines. A balanced binary tree with a billion keys has about 30 levels, and every level can cost a separate block read. A B-tree (Bayer & McCreight, 1972) packs many keys into each node instead, so that one node fills one block.

h ≤ log⁡tn+12h\ \le\ \log_t\frac{n+1}{2}
The height bound (CLRS, Theorem 18.1). Level i≥1i\ge1 has at least 2ti−12t^{i-1} nodes with at least t−1t-1 keys each, so n≥1+(t−1)∑i=1h2ti−1=2th−1n\ge1+(t-1)\sum_{i=1}^{h}2t^{i-1}=2t^h-1.

A search reads one node per level and does the comparisons inside it in fast memory. An insertion that overfills a node splits it around its median key, which moves up into the parent; CLRS splits every full node it passes on the way down, so a parent always has room, and the tree grows only when the root splits, which keeps all leaves at the same depth. A deletion borrows a key from a sibling, or merges with one, to keep every node at least t−1t-1 keys full.

Predict before you look

A B-tree with minimum degree t=500t=500 (every node except the root holds 499 to 999 keys) stores 10910^9 keys. How many nodes does a search read, root included?

Show the answer

4

The height is at most ⌊log⁡500(5⋅108)⌋=3\lfloor\log_{500}(5\cdot10^8)\rfloor=3, and it cannot be 2, because three levels of nodes with at most 1,000 children each hold at most 10003−1<1091000^3-1<10^9 keys. So the height is exactly 3: four levels, four node reads. In practice the top levels stay in RAM, leaving one or two disk reads, where a balanced binary tree would need about 30.

A B+ tree keeps all records in the leaves and only separator keys in the internal nodes, which raises the fan-out, and it links the leaves in key order, so a range query descends once and then reads consecutive leaves. Relational databases such as InnoDB, PostgreSQL and SQLite index with B+ tree variants, as do many file systems. In memory, B-trees win on cache lines too: Rust's standard BTreeMap and Abseil's btree_map for C++ are B-trees, and Linux tracks each process's virtual memory areas in the maple tree, a B-tree variant for ranges. The Optimal lesson B-Trees & B+ Trees proves the I/O bounds.

Recognizing it

Reach for a balanced tree, almost always the library's, when:

  • you need order and guaranteed O(log⁡n)O(\log n) on inputs you do not control: sorted insertions, timestamps, adversarial tests;
  • elements leave from the middle while you keep asking for the minimum, maximum, floor or ceiling: a multiset;
  • each request gets the best-fitting resource, the smallest capacity ≥\ge its demand, which is then removed;
  • the data lives on disk or does not fit in memory: a B-tree or B+ tree.
Problem (in brief)Key ideaCost
The median of every window of kk consecutive valuesTwo multisets, the lower and the upper half, rebalanced after each stepO(nlog⁡k)O(n\log k)
The skyline of overlapping rectanglesSweep the xx-events; a multiset of active heights gives the current maximum; erase one copy when a rectangle endsO(nlog⁡n)O(n\log n)
Give each job the smallest free machine whose capacity is at least its demandlower_bound in a multiset of capacities, then erase that copyO(nlog⁡n)O(n\log n)
The kk-th smallest value under insertions and deletionsAn order-statistic tree, or offline a Fenwick tree over compressed valuesO(log⁡n)O(\log n) per operation
Index a billion rows by key, with range scansA B+ tree with block-sized nodesO(log⁡Bn+k/B)O(\log_B n+k/B) block reads
Five common shapes of a balanced-tree problem.
cpp
#include <iterator>
#include <set>
#include <vector>
using namespace std;

// Median of every window of length k, in O(n log k)
vector<double> windowMedians(const vector<int>& a, int k) {
    multiset<int> lo, hi;                         // lo: smaller half, |lo| = |hi| or |hi| + 1
    vector<double> out;
    for (int i = 0; i < (int)a.size(); ++i) {
        if (lo.empty() || a[i] <= *lo.rbegin()) lo.insert(a[i]); else hi.insert(a[i]);
        if (i >= k) {                             // erase ONE copy of the value leaving
            auto it = lo.find(a[i - k]);
            if (it != lo.end()) lo.erase(it); else hi.erase(hi.find(a[i - k]));
        }
        while (lo.size() > hi.size() + 1) { hi.insert(*lo.rbegin()); lo.erase(prev(lo.end())); }
        while (hi.size() > lo.size())     { lo.insert(*hi.begin());  hi.erase(hi.begin()); }
        if (i >= k - 1)
            out.push_back(k % 2 ? *lo.rbegin() : (*lo.rbegin() + (double)*hi.begin()) / 2);
    }
    return out;
}

Every element of lo is at most every element of hi, so the median is the largest element of lo (or the average of the two middle values when kk is even). Erasing by iterator removes one copy; erase(value) would remove them all. Tested against sorting every window.

Check your understanding

2⋅1052\cdot10^5 operations arrive: insert a value, delete one copy of an arbitrary value xx, report the current maximum. Which choice is the most direct?

  1. A std::priority_queue alone
  2. A std::multiset: insert, erase(find(x)) and *rbegin()
  3. An unordered_multiset
  4. A sorted std::vector
Show the answer

B. A std::multiset: insert, erase(find(x)) and *rbegin()

A balanced BST that keeps duplicates does all three in O(log⁡n)O(\log n): insertion, erasing one iterator, and reading the last element.

Key takeaways

  • A rotation changes three child pointers in O(1)O(1) time, keeps the inorder sequence (and so the BST property), and moves one subtree up a level and another down.
  • AVL trees keep sibling heights within one: minimum sizes are Fibonacci numbers, so h<1.4405log⁡2(n+2)−1.3277h<1.4405\log_2(n+2)-1.3277; an insertion needs at most one single or double rotation, a deletion up to O(log⁡n)O(\log n).
  • Red-black trees forbid red-red edges and equalize black counts: h≤2log⁡2(n+1)h\le2\log_2(n+1), at most 2 rotations per insertion and 3 per deletion, and O(1)O(1) amortized recolorings. They are the usual library choice.
  • B-trees keep all leaves at one depth with nodes of t−1t-1 to 2t−12t-1 keys, so h≤log⁡tn+12h\le\log_t\frac{n+1}{2} and a billion keys fit in four levels; B+ trees keep the records in linked leaves for range scans.
  • Use the library's ordered map or multiset; write your own balanced tree only to augment it or to split and join it.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

After an AVL insertion, the first unbalanced ancestor zz is repaired with one single or double rotation. Why does nothing above zz need repair?

  1. The repaired subtree is back to its height before the insertion, so no ancestor's balance factor changes
  2. The root of an AVL tree is always balanced
  3. Heights of nodes above zz are not stored
  4. AVL trees tolerate balance factors of ±2\pm2 above the first repair
Show the answer

A. The repaired subtree is back to its height before the insertion, so no ancestor's balance factor changes

The insertion raised the height of zz's taller side by one; the single or double rotation lowers it by one again. Every ancestor of zz sees its subtree heights exactly as before the insertion, so their balance factors are unchanged.

Question 2

Which comparison between AVL trees and red-black trees is correct?

  1. Red-black trees guarantee height at most about 1.44log⁡2n1.44\log_2 n
  2. AVL trees are never taller than about 1.44log⁡2n1.44\log_2 n, while red-black deletions need at most 3 rotations against AVL's O(log⁡n)O(\log n)
  3. AVL trees need fewer rotations per deletion than red-black trees
  4. Red-black trees store each node's height
Show the answer

B. AVL trees are never taller than about 1.44log⁡2n1.44\log_2 n, while red-black deletions need at most 3 rotations against AVL's O(log⁡n)O(\log n)

The AVL invariant is stricter, so AVL trees are shorter (1.44log⁡2n1.44\log_2 n against 2log⁡2n2\log_2 n), but it is also costlier to restore after a deletion, which may rotate at every level, whereas a red-black deletion rotates at most 3 times.

Question 3

Why do databases index with B+ trees rather than red-black trees?

  1. Each node visit can cost a block read, and wide nodes cut the height for a billion keys from about 30 levels to 3 or 4, while linked leaves make range scans sequential
  2. B+ trees make fewer key comparisons than red-black trees
  3. Red-black trees cannot store string keys
  4. B+ trees never need any rebalancing
Show the answer

A. Each node visit can cost a block read, and wide nodes cut the height for a billion keys from about 30 levels to 3 or 4, while linked leaves make range scans sequential

The cost that matters on disk is the number of blocks read, not the number of comparisons. A node with hundreds of keys fills a block, so a search reads O(log⁡Bn)O(\log_B n) blocks, a factor of about log⁡2B\log_2 B fewer than a binary tree.

Question 4

A right rotation at yy, whose left child is xx, changes which of these?

  1. The inorder sequence of the keys
  2. The set of keys in the tree
  3. The depths of the nodes in two of the subtrees, and the parent of the middle one
  4. The height of every node in the tree
Show the answer

C. The depths of the nodes in two of the subtrees, and the parent of the middle one

Subtree α\alpha moves up a level, γ\gamma moves down a level, and β\beta changes parent from xx to yy at the same depth. The inorder sequence, and hence the BST property, is unchanged; heights change only at xx, yy and their ancestors.

Go deeper

Further reading

  • G. M. Adel'son-Vel'skii & E. M. Landis, "An algorithm for the organization of information," Soviet Mathematics Doklady 3 (1962), 1259–1262.
  • L. J. Guibas & R. Sedgewick, "A dichromatic framework for balanced trees," Proceedings of the 19th IEEE Symposium on Foundations of Computer Science (1978), 8–21.
  • R. Bayer & E. McCreight, "Organization and maintenance of large ordered indexes," Acta Informatica 1 (1972), 173–189.
  • T. H. Cormen, C. E. Leiserson, R. L. Rivest & C. Stein, Introduction to Algorithms, 4th ed. (MIT Press, 2022), chapters 13 and 18.