Why balance matters
Every operation of a binary search tree walks one root-to-node path, so it costs O(h), where h is the height. Insert the keys 1, 2, 3, …, n in that order and a plain BST becomes a chain of height n − 1: search is then a linear scan with extra pointer chasing. Nothing about the keys is wrong; only the order they arrived in was unlucky, and real data (timestamps, auto-increment IDs, sorted files) arrives in that order all the time.
A balanced search tree does a little extra work on every update so that the height stays O(log n) whatever the order. The AVL tree (Adelson-Velsky and Landis, 1962) was the first. It is still the clearest one to study, because its rule is a single number per node.
Heights and balance factors
This lesson, the lab and all four implementations count height in edges, as in the BST lesson:
- an empty subtree has height −1, a leaf has height 0;
height(node) = 1 + max(height(left), height(right));- the balance factor is
bf(node) = height(left) − height(right).
AVL invariant: every node has bf ∈ {−1, 0, +1}. The two subtrees of any node differ in height
by at most one. Positive means left-heavy, negative right-heavy.
Each node stores its own height, so a balance factor costs two field reads, not a traversal. The price is keeping those stored heights correct after every change, and that is exactly where rebalancing hooks in.
Rotations
A rotation changes the shape of a subtree in O(1) without changing its inorder sequence.
y x
/ \ rotate right at y / \
x C ───────────────▶ A y
/ \ ◀─────────────── / \
A B rotate left at x B C
Read the keys left to right in both pictures: A < x < B < y < C either way. Only three links
change: y.left becomes B, x.right becomes y, and whoever pointed at y now points at x.
Subtree B, the "middle" one, is the only part that changes parent. Afterwards only y and x need
new heights, y first because it is now the lower of the two.
In the lab, a rotation is one step: the node moving up is violet, the node moving down teal, and because nodes are placed left to right by inorder rank you can watch every key keep its column while the levels change.
Insert: the four cases
Insert starts as a plain BST insert: compare, descend, attach a new leaf. Then the recursion unwinds, and every node on the path back to the root does three things:
insert(node, key):
if node is empty: return new leaf # height 0
if key < node.key: node.left = insert(node.left, key)
elif key > node.key: node.right = insert(node.right, key)
else: return node # duplicate: nothing changes
return rebalance(node)
rebalance(node):
node.height = 1 + max(height(node.left), height(node.right))
bf = height(node.left) − height(node.right)
if bf > 1: # left-heavy
if bf(node.left) < 0: node.left = rotate_left(node.left) # LR
return rotate_right(node) # LL
if bf < −1: # right-heavy
if bf(node.right) > 0: node.right = rotate_right(node.right) # RL
return rotate_left(node) # RR
return node
After an insert, the first node on the way up whose balance factor leaves −1…+1 has bf = +2 or
bf = −2. Which rotation fixes it depends on the sign of the heavy child's balance factor:
| Node bf | Heavy child bf | Shape | Case | Fix |
|---|---|---|---|---|
| +2 | +1 | left child leans left (a straight line) | LL | rotate right at the node |
| −2 | −1 | right child leans right | RR | rotate left at the node |
| +2 | −1 | left child leans right (a zig-zag) | LR | rotate left at the child, then right at the node |
| −2 | +1 | right child leans left | RL | rotate right at the child, then left at the node |
The single rotation fails on a zig-zag: rotating right at the node of an LR shape just produces the
mirror-image zig-zag. The first half of the double rotation straightens the zig-zag into an LL
shape; the second half is the ordinary LL fix. Each preset in the lab isolates one case with three
keys: 30, 20, 10 (LL), 10, 20, 30 (RR), 30, 10, 20 (LR) and 10, 30, 20 (RL). All four end as
the same tree, 20 with children 10 and 30.
At most one rotation per insert
Look at the subtree rooted at the unbalanced node before the insert. Say its height was h. The insert made it h + 1, which is what unbalanced it. In every one of the four cases, the rotation produces a subtree of height h again. So every ancestor above sees its child's height back at the old value: nothing above can be out of balance. Hence an insert performs at most one single or one double rotation, followed only by height updates. The Mixed preset shows this: inserting 5 unbalances 30, deep inside the tree, and one right rotation there leaves the root's balance untouched.
(The implementations still recompute heights all the way up, which is simpler and costs O(log n) anyway. They skip the whole way back up after a duplicate, when nothing changed.)
Delete
Delete is the BST delete (leaf, one child, two children via the inorder successor) followed by the
same rebalance on the way up. The four cases are identical, plus one new situation: the heavy
child can have balance factor 0, which deletion can produce but insertion cannot; it is handled as
LL (or RR). The difference is that a rotation after a delete can lower the subtree's height, so the
ancestor above may become unbalanced in turn: one delete can need a rotation at every level, O(log n)
of them. The lab and the four implementations cover insert, search and the invariant check; delete
adds no new rotation to see, only more of the same.
How tall can an AVL tree be?
Ask the reverse question: what is the fewest nodes N(h) an AVL tree of height h can have? The sparsest such tree has a root, one subtree of height h − 1 and, as lopsided as allowed, the other of height h − 2, each of them as sparse as possible:
N(0) = 1, N(1) = 2, N(h) = N(h − 1) + N(h − 2) + 1
1, 2, 4, 7, 12, 20, 33, 54, … N(h) = F(h + 3) − 1 (F = Fibonacci: 1, 1, 2, 3, 5, 8, …)
These sparsest trees are called Fibonacci trees. Fibonacci numbers grow like φʰ with φ ≈ 1.618, so
n ≥ N(h) ≈ φʰ⁺³/√5, which gives h ≤ log_φ n + O(1) ≈ 1.44 log₂ n. Knuth's exact form, counting
levels rather than edges, is levels < 1.4405 log₂(n + 2) − 0.3277; all four test suites assert it on
random trees. For a million keys an AVL tree has at most 28 levels, against 20 for a perfect tree
and up to a million for an unlucky BST. Inserting 1 … 2ᵏ − 1 in sorted order even builds a perfect
tree: the Sorted inserts stay balanced preset ends with 1 … 7 at height 2 after four rotations.
Complexity
| Operation | AVL tree | Plain BST (worst case) |
|---|---|---|
| search | O(log n) | O(n) |
| insert | O(log n), at most 1 single or double rotation | O(n) |
| delete | O(log n), up to O(log n) rotations | O(n) |
| min, max, successor | O(log n) | O(n) |
| invariant check | O(n) | O(n) |
| extra space | one height per node (a byte would do); O(log n) recursion stack | none |
Every bound is a worst case, not an average: that is the point of balancing.
Red-black trees
A red-black tree is another balanced BST, with a looser rule enforced by colouring every node red or black:
- The root is black, and the empty leaves (null links) count as black.
- A red node has no red child.
- Every path from a node down to an empty leaf passes the same number of black nodes, its black-height.
Rule 3 says the tree is perfectly balanced if you ignore red nodes; rule 2 says red nodes can at most
double a path's length. So the longest path is at most twice the shortest, and the height is at most
2 log₂(n + 1). That is a weaker guarantee than AVL's 1.44 log₂ n, so searches can be slightly
deeper. In exchange, repairs are cheaper: an insert does at most two rotations and a delete at most
three, with the rest done by recolouring (which can walk up the tree but is O(1) amortized). That
makes red-black trees a common default for general-purpose ordered maps with many updates; AVL trees
suit lookup-heavy workloads a little better. Both are O(log n) for everything.
B-trees and B+ trees
When data lives on disk or SSD, the cost that matters is the number of pages read, not the number of comparisons. A B-tree (Bayer and McCreight, 1972) stores many keys per node, sized to fill a page:
- a node with k keys has k + 1 children, and keys separate the children's ranges, like a BST node generalised to many keys;
- every node except the root is at least half full (between t − 1 and 2t − 1 keys for a minimum degree t);
- all leaves are at the same depth. The tree grows at the root (a full node splits and pushes its middle key up), never by making one branch longer.
With hundreds of keys per node, the height is O(log_t n): a few levels cover billions of keys, and the top levels usually stay cached in memory. A B+ tree keeps all records in the leaves, uses the inner nodes only for routing, and links the leaves left to right so a range scan is a sequential walk. B+ tree variants are the usual index structure in relational databases and appear in many file systems. In memory, wide nodes also help with cache lines, which is why some ordered containers use B-trees there too (not the standard ones covered below).
Comparison
| AVL tree | Red-black tree | B-tree / B+ tree | |
|---|---|---|---|
| Invariant | subtree heights differ by ≤ 1 | colour rules, equal black-height | nodes ≥ half full, leaves at one depth |
| Height bound | < 1.44 log₂ n | ≤ 2 log₂(n + 1) | O(log_t n), t = keys per node / 2 |
| Rotations per insert | ≤ 1 single or double | ≤ 2 | none (node splits instead) |
| Rotations per delete | O(log n) | ≤ 3 | none (merges and borrows) |
| Stored per node | a height | a colour bit | up to 2t − 1 keys, 2t children |
| Typical home | in-memory, lookup-heavy | in-memory library maps and sets | databases, file systems (disk pages) |
Built-in ordered collections
You will rarely write a balanced tree for production code; you will choose between the library ones.
| Language | Ordered set / map | What the documentation guarantees |
|---|---|---|
| C# | SortedSet<T>, SortedDictionary<TKey, TValue> |
Documented as binary search trees with O(log n) operations; in current .NET both are implemented as red-black trees. SortedList<TKey, TValue> is different: two sorted arrays, O(log n) lookup but O(n) insert and remove. |
| Java | TreeMap<K, V>, TreeSet<E> |
The TreeMap Javadoc states it is a red-black tree with guaranteed log(n) containsKey, get, put and remove; TreeSet is backed by a TreeMap. |
| C++ | std::set, std::map (and multi versions) |
The standard fixes the interface and logarithmic complexity, not the structure. The major implementations (libstdc++, libc++, Microsoft's STL) typically use red-black trees, but that is implementation-defined. |
| Python | none in the standard library | dict and set are hash tables (no order by key). For a sorted sequence, the bisect module searches a sorted list in O(log n), but insort must shift elements: O(n) per insert. Third-party packages such as sortedcontainers exist; they are not part of the standard library, and this course does not depend on them. |
All of these give you the AVL tree's guarantees (worst-case O(log n), iteration in key order, floor and ceiling queries) without any rotation code of your own.
The teaching implementation
AvlTree / avl_tree follows the pseudocode above in all four languages: recursive Insert that
returns the subtree's new root, Rebalance with the four cases, RotateLeft / RotateRight, an
iterative Contains, and IsValid, which checks order, stored heights and balance factors in one
postorder pass. The C++ version owns its nodes through std::unique_ptr, so a rotation moves
ownership of three links. Each language runs one shared fixture that pins the exact shape (preorder),
height and rotation count of every case, and 300 random insert/search sequences against its own
sorted set (SortedSet<int>, set + sorted, TreeSet, std::set), checking the invariants after
every operation.
Language notes
- C#: a
ref bool addedparameter reports whether the recursive insert created a node.Node?nullable annotations make the "child exists" assumptions explicit (node.Left!in the rotation cases, where the balance factor guarantees the child). - Python: recursion depth is not a concern here, because an AVL tree of any size you can hold in memory is less than about 60 levels deep, far below the default recursion limit of 1000.
- Java:
Integer.MIN_VALUEmarks a broken subtree in the checker; the bounds arelongso that keys equal toInteger.MIN_VALUEorMAX_VALUEstill fit strictly inside them. - C++:
std::optional<int>expresses both "no bound" and "broken" without sentinels.
Common mistakes
- Updating heights in the wrong order after a rotation. The node that moved down must be updated first; the node that moved up depends on it.
- Forgetting to relink the parent. The rotation returns a new subtree root; if the caller does not
store it (
node.left = insert(...)), the rotated subtree is lost. - Using a single rotation on a zig-zag (LR or RL). It only mirrors the problem.
- Mixing height conventions. Leaf height 0 with empty −1, or leaf 1 with empty 0, both work; mixing them makes every balance factor off by one at the leaves.
- Recomputing heights by traversal.
height()as a recursive function makes every insert O(n).
Edge cases
- Duplicates: rejected, nothing changes, no rotation.
- An empty tree is a valid AVL tree;
checkreturns true and search returns false. - Two keys: a root and one child, balance ±1, still valid; the third key decides whether a rotation happens.
- Extreme keys (−999 and 999 in the lab,
intlimits in code) need strict bounds in the checker.
Worked practice
1. Insert 10, 20, 30, 40, 50 into an empty AVL tree. Give the final preorder and the number of rotations.
Answer
30 makes 10 right-heavy (−2) with its right child leaning right: RR, rotate left at 10, giving 20
with children 10 and 30. 40 goes under 30. 50 makes 30 right-heavy (−2): RR again, rotate left at 30.
Final tree: 20, left 10, right 40 with children 30 and 50. Preorder 20 10 40 30 50, two rotations,
height 2. A plain BST would have height 4.
2. A node has bf = +2 and its left child has bf = −1. Name the case and the rotations, in order.
Answer
LR: rotate left at the left child (straightening the zig-zag into an LL shape), then rotate right at the node. In the lab's Case LR preset that is "rotate 10 left", then "rotate 30 right".
3. What is the smallest number of keys an AVL tree of height 4 (edges) can hold? And a plain BST?
Answer
N(4) = N(3) + N(2) + 1 = 7 + 4 + 1 = 12 for the AVL tree. A plain BST needs only 5: a chain.
4. Why can one insert never trigger rotations at two different nodes?
Answer
The rotation at the lowest unbalanced node returns that subtree to the height it had before the insert. Every ancestor's balance factor depended only on that height, which is unchanged, so every ancestor is as balanced as before the insert.
5. You need a sorted map in Python with frequent inserts and range queries over 10⁶ keys. What are your standard-library options and their costs?
Answer
A sorted list with bisect: O(log n) to find a position and to answer range boundaries, but O(n)
to insert because elements shift (fast in practice thanks to memmove, but still linear). Or a dict
plus sorting when needed. The standard library has no balanced tree; a third-party sorted collection
or a database index would be the next step, by choice and not by default.
Summary
- An AVL tree is a BST where every node's subtrees differ in height by at most one.
- Insert as in a BST, then on the way up update heights and fix the first node with bf = ±2.
- LL and RR need one rotation, LR and RL two; rotations preserve the sorted order and take O(1).
- Height stays below about 1.44 log₂ n, so search, insert and delete are worst-case O(log n).
- Red-black trees relax the balance (height ≤ 2 log₂(n + 1)) for cheaper updates and back the ordered collections of .NET, Java and typically C++; B-trees widen nodes to match disk pages.
- Python's standard library has no balanced tree: use
bisecton a list, or reach outside it.