Search

Search papers and lessons

Balanced Binary Tree

Level 3 · 12 min read

A balanced binary tree rearranges itself after each change so that no node's two subtrees differ much in height, which keeps lookups near log n even when keys arrive in the worst order.

On this page

  • Colour = topic mix
  • Algorithms
  • Discrete math
  • Sign in to see your progress

TL;DR

A balanced binary tree is a binary search tree that corrects its own shape after every insert and delete, so that the two subtrees of any node never differ much in height. The AVL tree is the classic version: its height stays below about 1.44 times log⁡2n\log_2 n. Lookups, inserts and deletes therefore cost O(log⁡n)O(\log n) in the worst case, even when the keys arrive in sorted order.

Where you'll see it: in the ordered map and ordered set types of many programming libraries, where red-black trees and AVL trees are the two standard choices, and in in-memory indexes that must stay sorted under constant updates.

Intuition

The problem: the shape depends on the input order

A plain binary search tree has a lookup cost equal to its height. The shape of the tree depends on the order the keys were inserted. Insert 1, 2, 3, 4, 5 into an empty tree and each key lands at the far right, so the tree is a chain five levels tall. Real data does this often. Timestamps only increase, auto-generated IDs only increase, and sorted files are loaded in sorted order. A million sorted keys can produce a tree a million levels tall, and a lookup can take a million comparisons.

The programmer does not control the input order, so the fix has to live in the tree itself.

1020304050600204060number of keys nheight (levels)
  • plain tree, sorted input: height n
  • AVL worst case: about 1.44 log2 n
The sorted-input chain grows in a straight line. The balanced tree grows only logarithmically, so doubling n adds about one more level.

A rotation changes the shape, not the order

The repair tool is the rotation. Picture a mobile hanging from a hook: lift a different piece to be the top, and the other pieces swing to new positions, but their left-to-right order does not change. A rotation does this to a small group of nodes. Two keys swap parent and child, one subtree moves across, and the left-to-right order of the keys is unchanged. Because the inorder sequence is unchanged, the search-tree rule still holds, and a rotation takes only a handful of pointer changes.

After each insert, the tree checks the heights along the path back to the root. When it finds a node that has become too lopsided, it rotates there. The result is a tree that tolerates any insert order and still keeps every lookup short.

flowchart TD
  A[Insert key as a normal leaf] --> B[Walk back up, updating heights]
  B --> C{Any node now off by two?}
  C -- no --> D[Done]
  C -- yes --> E[Rotate at the lowest such node]
  E --> D

The math

Definition

Definition: AVL tree

Use the height convention from Binary Tree: an empty tree has height −1-1 and a single node has height 00. For a node vv, let h(left)h(\text{left}) and h(right)h(\text{right}) be the heights of its two subtrees. The balance factor of vv is

bf(v)=h(left)−h(right).\mathrm{bf}(v) = h(\text{left}) - h(\text{right}).

An AVL tree is a binary search tree in which every node has bf(v)∈{−1,0,1}\mathrm{bf}(v) \in \{-1, 0, 1\}. Equivalently, the two subtrees of every node differ in height by at most one.

Only the balance factor is stored per node, and it is enough. An insert or delete changes heights along one path, so the balance factors that might break lie on that path too.

Why the height stays logarithmic

Let N(h)N(h) be the fewest nodes an AVL tree of height hh can have. The smallest such tree has a root, a smallest tree of height h−1h-1 and a smallest tree of height h−2h-2. The heights must differ by at most one, so one side must reach h−1h-1 and the other can drop to h−2h-2. This gives the recurrence

N(0)=1,N(1)=2,N(h)=N(h−1)+N(h−2)+1.N(0) = 1, \qquad N(1) = 2, \qquad N(h) = N(h-1) + N(h-2) + 1.

The values run 1, 2, 4, 7, 12, 20, 33, 54. They grow by a factor close to the golden ratio φ≈1.618\varphi \approx 1.618 each level, so N(h)N(h) grows like φh\varphi^h times a constant. If the tree has nn nodes then n≥N(h)n \ge N(h), which gives h<log⁡φn+ch \lt \log_\varphi n + c. Since log⁡φn=log⁡2n/log⁡2φ\log_\varphi n = \log_2 n / \log_2 \varphi and 1/log⁡2φ≈1.441 / \log_2 \varphi \approx 1.44, the height satisfies

h<1.44log⁡2(n+2).h \lt 1.44 \log_2 (n + 2).

The exact constant in the standard bound differs slightly, but the 1.44 factor is the important part. Every lookup, insert and delete walks one path of at most this many nodes.

Rotations

A right rotation at a node zz whose left child is yy works like this. Let AA, BB and CC be the three subtrees, so the keys satisfy A<y<B<z<CA \lt y \lt B \lt z \lt C. Before the rotation, yy is the left child of zz and yy has children AA and BB. After the rotation, yy is the root of the piece with children AA and zz, and zz has children BB and CC.

Inorder reads A,y,B,z,CA, y, B, z, C both before and after. The search property is kept, and only a few child pointers change, so a rotation costs O(1)O(1). A left rotation is the mirror image.

Insertion

Insert the key the ordinary way, then walk back up and update heights. Let zz be the lowest node whose balance factor has become ±2\pm 2. Let yy be its taller child and xx the taller child of yy. There are four cases:

  1. Left-left (yy is the left child of zz, xx is the left child of yy): right-rotate at zz.
  2. Right-right (yy is the right child of zz, xx is the right child of yy): left-rotate at zz.
  3. Left-right (xx is the right child of yy): left-rotate at yy, then right-rotate at zz.
  4. Right-left (xx is the left child of yy): right-rotate at yy, then left-rotate at zz.

After one of these fixes, the subtree has the same height it had before the insert, so no ancestor is unbalanced. An insert therefore needs at most one rotation pair. A delete can leave imbalance at several nodes on the way back up, so it may need a rotation at each level of the path. The total work is still O(log⁡n)O(\log n).

Worked examples

Example
Insert 3, 2, 1: the left-left case
  1. Insert 3. The tree is a single node, height 0.
  2. Insert 2 as the left child of 3. At node 3, h(left)=0h(\text{left}) = 0 and h(right)=−1h(\text{right}) = -1, so bf=1\mathrm{bf} = 1. That is allowed.
  3. Insert 1 as the left child of 2. Node 2 now has height 1. At node 3, h(left)=1h(\text{left}) = 1 and h(right)=−1h(\text{right}) = -1, so bf=2\mathrm{bf} = 2. Node 3 is the lowest unbalanced node.
  4. The taller child of 3 is 2, and the taller child of 2 is 1, on the left of both. This is the left-left case, so right-rotate at 3.
  5. The result has root 2, left child 1 and right child 3. Every balance factor is 0 and the height is 1 instead of 2.
  6. Check the order: inorder before the rotation was 1, 2, 3, and after it is still 1, 2, 3.

Interpretation: with three keys the difference is small, but this is the mechanism that stops a chain from forming. The rotation happened the moment the tree became lopsided, not later.

Example
Insert 1 through 7 in order

Start from an empty AVL tree and insert 1, 2, 3, 4, 5, 6, 7 in that order. A plain binary search tree would become a chain of height 6. The AVL tree rotates four times:

  1. Insert 3 after 1 and 2. Node 1 has balance −2-2 (right-right). Left-rotate at 1. The tree is root 2 with children 1 and 3.
  2. Insert 5 after 3 and 4. Node 3 has balance −2-2 (right-right). Left-rotate at 3. The tree is root 2, with left child 1 and right child 4. Node 4 has children 3 and 5.
  3. Insert 6. Node 2 has balance −2-2 (right-right), since its right subtree has height 2 and its left has height 0. Left-rotate at 2. The tree is root 4, with left child 2 (children 1 and 3) and right child 5 (with right child 6).
  4. Insert 7. Node 5 has balance −2-2 (right-right). Left-rotate at 5. The final tree is root 4, with children 2 and 6, and the leaves 1, 3, 5, 7 underneath.

Interpretation: the final tree has height 2 for seven keys, which is the best possible. The same input gave height 6 in the plain tree. The keys were inserted in the worst order, yet the shape is perfectly balanced.

Example
A log of one million increasing timestamps

Suppose a log stores one million records with timestamps that only increase, and each lookup is by timestamp.

  1. In a plain binary search tree every insert goes to the far right, so the height is 999,999. A lookup for the newest record takes about one million comparisons.
  2. In an AVL tree the height is below 1.44log⁡2(106+2)1.44 \log_2 (10^6 + 2). Since log⁡2106≈19.93\log_2 10^6 \approx 19.93, the bound is about 1.44×19.93≈28.71.44 \times 19.93 \approx 28.7. So the height is at most 28 levels.
  3. A lookup therefore takes at most about 28 comparisons, however the timestamps arrived.

Interpretation: the balanced tree turns a million-step worst case into a 28-step worst case. The cost of this guarantee is paid in rotations during inserts, which are cheap, and in the extra bookkeeping of storing balance information.

Tradeoffs and failure modes

A balanced tree is worth its extra code when the worst case matters. When it does not, simpler structures can be better.

SituationWhat goes wrongBetter choice
Keys arrive sorted or nearly sorted, and lookups must stay fastA plain tree becomes a chain, so lookups cost O(n)O(n)An AVL tree or a red-black tree
Keys arrive in random order and the average cost is enoughA plain tree is fine on average, and it is simpler to writeA plain binary search tree
Reads dominate and writes are rareRed-black trees rebalance more cheaply on insert, but their lookups can be a little deeperAn AVL tree, whose height is smaller
Writes are frequent and rotations are a bottleneckAVL trees rotate more often on delete than red-black treesA red-black tree, which is what many standard libraries use
Data lives on disk and each read fetches a blockA binary node per disk read wastes most of each readA B-Tree, with many keys per node
You only need exact-match lookup and never need orderTree bookkeeping costs time and memoryA hash table
Many threads update the structure at onceRotations touch several nodes, so locking is awkwardA Skip List, which is often simpler to make concurrent

Some failure modes are common in practice. The classic bug in a rotation is losing the middle subtree BB: if you move the wrong child, the inorder order breaks and searches silently return wrong answers. Heights must be updated bottom-up, with the node that moved down updated before the node that moved up. Storing a stale height or balance factor makes the tree look balanced when it is not, so the guarantee quietly disappears. Finally, a single delete can unbalance several ancestors, so the repair walk must continue to the root instead of stopping after the first rotation.

History

Georgy Adelson-Velsky and Evgenii Landis, two Soviet mathematicians, published the AVL tree in 1962. It was the first self-balancing binary search tree, and it gave a worst-case guarantee where earlier binary search trees gave only an average-case one. Donald Knuth discusses it in The Art of Computer Programming, Volume 3.

The idea caught on because it solved a real problem. Programs needed sorted data that stayed fast under any input order, and the AVL tree was the first structure to promise that in theory and in code. Later trees traded some strictness for fewer rotations. Rudolf Bayer and Edward McCreight introduced B-trees in 1972 for disk-based data. Leo Guibas and Robert Sedgewick presented the red-black tree in 1978, and it is now the default in many standard libraries because it rotates less on updates.

Check yourself

QuestionRecall: what condition must every node of an AVL tree satisfy?Show answer

For every node, the heights of its left and right subtrees differ by at most one. Equivalently, its balance factor, left height minus right height, is −1-1, 00 or 11. This is a local rule, but it is enough to keep the whole tree's height logarithmic.

QuestionComputation: what is the fewest number of nodes an AVL tree of height 3 can have?Show answer

Use N(0)=1N(0) = 1, N(1)=2N(1) = 2 and N(h)=N(h−1)+N(h−2)+1N(h) = N(h-1) + N(h-2) + 1. Then N(2)=2+1+1=4N(2) = 2 + 1 + 1 = 4, and N(3)=4+2+1=7N(3) = 4 + 2 + 1 = 7. So the answer is 7. Check it by building the tree: a root, one subtree of height 1 with the fewest possible nodes (2) and one subtree of height 2 with the fewest possible nodes (4). The two subtrees differ in height by one, so the root is allowed, and the total is 1+2+4=71 + 2 + 4 = 7.

QuestionWhy: why does a rotation keep the tree a valid binary search tree?Show answer

A rotation changes which key is the parent of which, but it never changes the inorder sequence of keys. In the right rotation above, inorder reads A,y,B,z,CA, y, B, z, C before and after. A binary search tree is valid exactly when its inorder traversal is sorted, so the sorted order, and with it the search rule, survives the rotation.

QuestionApplied: you must store a sorted set of IDs that arrive in increasing order, on a single machine, and look up IDs often. Would you choose a plain binary search tree, an AVL tree or a hash table?Show answer

A plain binary search tree would turn into a chain, because each new ID is larger than all earlier ones, and lookups would slow to O(n)O(n). A hash table gives fast exact lookups but loses the sorted order, which you need. An AVL tree, or a red-black tree, keeps the set sorted with O(log⁡n)O(\log n) lookups regardless of the arrival order. If the set grows very large and lives on disk, a B-tree is better still.

Sources