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 . Lookups, inserts and deletes therefore cost 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.
- plain tree, sorted input: height n
- AVL worst case: about 1.44 log2 n
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
Use the height convention from Binary Tree: an empty tree has height and a single node has height . For a node , let and be the heights of its two subtrees. The balance factor of is
An AVL tree is a binary search tree in which every node has . 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 be the fewest nodes an AVL tree of height can have. The smallest such tree has a root, a smallest tree of height and a smallest tree of height . The heights must differ by at most one, so one side must reach and the other can drop to . This gives the recurrence
The values run 1, 2, 4, 7, 12, 20, 33, 54. They grow by a factor close to the golden ratio each level, so grows like times a constant. If the tree has nodes then , which gives . Since and , the height satisfies
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 whose left child is works like this. Let , and be the three subtrees, so the keys satisfy . Before the rotation, is the left child of and has children and . After the rotation, is the root of the piece with children and , and has children and .
Inorder reads both before and after. The search property is kept, and only a few child pointers change, so a rotation costs . A left rotation is the mirror image.
Insertion
Insert the key the ordinary way, then walk back up and update heights. Let be the lowest node whose balance factor has become . Let be its taller child and the taller child of . There are four cases:
- Left-left ( is the left child of , is the left child of ): right-rotate at .
- Right-right ( is the right child of , is the right child of ): left-rotate at .
- Left-right ( is the right child of ): left-rotate at , then right-rotate at .
- Right-left ( is the left child of ): right-rotate at , then left-rotate at .
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 .
Worked examples
- Insert 3. The tree is a single node, height 0.
- Insert 2 as the left child of 3. At node 3, and , so . That is allowed.
- Insert 1 as the left child of 2. Node 2 now has height 1. At node 3, and , so . Node 3 is the lowest unbalanced node.
- 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.
- 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.
- 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.
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:
- Insert 3 after 1 and 2. Node 1 has balance (right-right). Left-rotate at 1. The tree is root 2 with children 1 and 3.
- Insert 5 after 3 and 4. Node 3 has balance (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.
- Insert 6. Node 2 has balance (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).
- Insert 7. Node 5 has balance (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.
Suppose a log stores one million records with timestamps that only increase, and each lookup is by timestamp.
- 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.
- In an AVL tree the height is below . Since , the bound is about . So the height is at most 28 levels.
- 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.
| Situation | What goes wrong | Better choice |
|---|---|---|
| Keys arrive sorted or nearly sorted, and lookups must stay fast | A plain tree becomes a chain, so lookups cost | An AVL tree or a red-black tree |
| Keys arrive in random order and the average cost is enough | A plain tree is fine on average, and it is simpler to write | A plain binary search tree |
| Reads dominate and writes are rare | Red-black trees rebalance more cheaply on insert, but their lookups can be a little deeper | An AVL tree, whose height is smaller |
| Writes are frequent and rotations are a bottleneck | AVL trees rotate more often on delete than red-black trees | A red-black tree, which is what many standard libraries use |
| Data lives on disk and each read fetches a block | A binary node per disk read wastes most of each read | A B-Tree, with many keys per node |
| You only need exact-match lookup and never need order | Tree bookkeeping costs time and memory | A hash table |
| Many threads update the structure at once | Rotations touch several nodes, so locking is awkward | A 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 : 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 , or . 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 , and . Then , and . 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 .
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 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 . 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 lookups regardless of the arrival order. If the set grows very large and lives on disk, a B-tree is better still.
Sources
- AVL tree (Wikipedia)
- Binary search tree (Wikipedia)
- B-tree (Wikipedia)
- Donald Knuth, The Art of Computer Programming, Vol. 3: Sorting and Searching