Sub topic 12
AVL or red-black: choosing between them
This chapter assumes you have read the earlier chapters on rotations, AVL insertion and deletion, and the red-black properties and fixups. You should be comfortable with O(log n) reasoning and with reading short Python programs. Both tree types guarantee O(log n) search, insertion and deletion. The decision rests on constant factors, the mix of reads and writes, and implementation effort.
What both designs guarantee
Each design keeps a small invariant that bounds the height. Rotations repair the invariant after an update.
- An AVL tree keeps the heights of every node's two subtrees within 1 of each other.
- A red-black tree colors nodes so that no red node has a red child and every root-to-leaf path has the same number of black nodes.
Both give worst-case O(log n) for search, insert and delete. They differ in how tight the height bound is and in how much repair work each update triggers.
Height bounds
The sparsest AVL tree of height h has N(h) = N(h-1) + N(h-2) + 1 nodes, which grows like Fibonacci numbers. Solving this gives:
- AVL: h < 1.44 · log2(n + 2) − 0.33
- Red-black: h ≤ 2 · log2(n + 1)
The red-black bound comes from black-height. The shortest root-to-leaf path is all black. The longest alternates red and black, so it is at most twice as long.
| Nodes (n) | Perfect tree height | AVL worst-case height | Red-black worst-case height |
|---|---|---|---|
| 1,000 | 10 | about 14 | about 20 |
| 1,000,000 | 20 | about 28 | about 40 |
The AVL tree is never taller than about 1.44 times the optimum. The red-black tree can be up to 2 times the optimum. Search cost is proportional to depth, so an adversarial worst case is roughly 40% slower on a red-black tree.
These are worst cases. For random insertions, both kinds of tree are typically only slightly taller than a perfect tree, and average depths differ much less than the bounds suggest. For sorted insertions, AVL trees end up noticeably more compact than red-black trees. If your workload is read-heavy and you build the tree from ordered data, the AVL tree's tighter shape is a real advantage.
Rebalancing work per update
The other side of the trade-off is repair cost. Keeping a tighter shape means doing more work to maintain it.
| Operation | AVL | Red-black |
|---|---|---|
| Insert, rotations | At most 1 (single or double) | At most 2 |
| Delete, rotations | Up to O(log n) | At most 3 |
| Insert, recoloring or height updates | O(log n) height updates along the path | O(log n) worst case, O(1) amortized |
| Extra data per node | Height (or a 2-bit balance factor) | 1 bit (color) |
Three points deserve attention.
- AVL insertion stops after one repair. Once a rotation fixes the lowest unbalanced node, the subtree returns to its pre-insertion height. Ancestors need no more rotations. The recursive code still walks back up to the root and updates heights on the way. That walk is cheap, but it is O(log n) work on every insert.
- AVL deletion can rotate at many levels. A rotation after deletion can leave the subtree one shorter than before, which can unbalance the parent, and so on up to the root. In practice this is rare, but the worst case is O(log n) rotations for one delete.
- Red-black deletion uses a constant number of rotations. Recoloring can still propagate up the tree, but recoloring is cheaper than rotating because it changes no pointers. This is the main reason red-black trees are described as better for write-heavy workloads.
Rotations are not free. They write to several nodes and can invalidate cached values. In concurrent or persistent (immutable) structures, every rotation also means copying nodes, so the rotation count matters more.
Measuring it yourself
The following script inserts the same keys into the AVL tree from earlier chapters, counts rotations, and compares the final height with the theoretical bounds. It is complete and runs as shown. The exact rotation counts for the random run change from run to run.
import math
import random
class Node:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
self.height = 1
rotations = 0
def height(n):
return n.height if n else 0
def update(n):
n.height = 1 + max(height(n.left), height(n.right))
def balance_factor(n):
return height(n.left) - height(n.right)
def rotate_right(y):
global rotations
rotations += 1
x = y.left
y.left = x.right
x.right = y
update(y)
update(x)
return x
def rotate_left(x):
global rotations
rotations += 1
y = x.right
x.right = y.left
y.left = x
update(x)
update(y)
return y
def rebalance(n):
update(n)
bf = balance_factor(n)
if bf > 1:
if balance_factor(n.left) < 0:
n.left = rotate_left(n.left)
return rotate_right(n)
if bf < -1:
if balance_factor(n.right) > 0:
n.right = rotate_right(n.right)
return rotate_left(n)
return n
def insert(n, key):
if n is None:
return Node(key)
if key < n.key:
n.left = insert(n.left, key)
elif key > n.key:
n.right = insert(n.right, key)
else:
return n
return rebalance(n)
def avl_bound(n):
return 1.44 * math.log2(n + 2) - 0.33
def rb_bound(n):
return 2 * math.log2(n + 1)
n = 50_000
workloads = (
("sorted", list(range(n))),
("random", random.sample(range(n), n)),
)
for name, keys in workloads:
rotations = 0
root = None
for k in keys:
root = insert(root, k)
print(
f"{name}: height={root.height}, rotations={rotations}, "
f"optimal={math.ceil(math.log2(n + 1))}, "
f"avl_bound={avl_bound(n):.1f}, rb_bound={rb_bound(n):.1f}"
)For both workloads the measured height is at or below the AVL bound and well below the red-black bound. The rotation count is also below the number of inserts, which matches the "at most one repair per insert" rule.
How they are used in practice
Standard libraries mostly pick red-black trees. Java's TreeMap and TreeSet, and the ordered containers std::map and std::set in the major C++ standard library implementations, use red-black trees. The Linux kernel ships a generic red-black tree. The usual reasons are the bounded rotations on delete and the small per-node overhead. The libraries must serve every kind of workload, and red-black trees have no bad case for updates.
AVL trees appear where lookups dominate or where the data is built once and queried many times. Boost.Intrusive, for example, offers both avltree and rbtree, so you can choose per container.
Neither is the usual choice for data on disk or very large in-memory indexes. A tree with one key per node touches a new cache line or disk page at almost every step. B-trees pack many keys into a node and are the standard answer there. If you only need lookups by exact key, a hash table is faster than either tree but gives no ordered iteration.
Implementation complexity
Red-black deletion is the hardest part of either structure. It has a double-black case analysis with four situations, each with a mirror image. AVL deletion reuses the same rebalance function as insertion, so the whole AVL implementation is shorter and easier to test. If you write a tree yourself and your workload is moderate, AVL is usually the lower-risk choice.
Red-black trees are easier to get away with in languages or libraries that already provide them. In that case you do not write the tree at all, and the question becomes which one your library offers.
A decision guide
Use these criteria in order:
- Use what exists. A tested library container beats your own tree.
- Check the data size and location. Disk-resident or very large data points to B-trees.
- Look at the read and write mix. Lookup-heavy workloads favor AVL. Update-heavy workloads favor red-black.
- Consider memory. AVL needs a height or balance factor per node. Red-black needs one color bit, which many implementations hide in an unused pointer bit.
- Consider simplicity. If the choice is otherwise close, the shorter AVL code is easier to verify.
Common mistakes
- Assuming one is asymptotically faster. Both are O(log n) for every operation. The difference is a constant factor.
- Claiming AVL deletion needs at most one rotation. That is true only for insertion. Deletion can rotate at every level up to the root.
- Forgetting that red-black trees are not strictly balanced. The left and right subtrees of a red-black node can differ in height by a factor of 2. Code that relies on a tight shape, such as an index-based "k-th element" shortcut without subtree sizes, will not hold.
- Testing only the final shape. After each update, check the invariants, not just that lookups succeed. The next chapter shows how.
Exercise
A service builds an ordered index once from a large sorted file, then answers millions of lookups and almost never updates it. A teammate suggests a red-black tree because "that is what the standard library uses." Which tree would you choose, and why?
Show answer
An AVL tree is the better fit. Lookup cost is proportional to depth, and the AVL worst-case height (about 1.44 · log2 n) is lower than the red-black worst case (about 2 · log2 n). Sorted insertion also tends to give AVL trees a more compact shape. The usual red-black advantage, fewer rotations on delete, does not matter because the index is almost never updated. If the data is large enough to be cache-unfriendly or disk-based, a B-tree would be a better choice than either.
Exercise
An AVL tree and a red-black tree each hold 1,000,000 keys. What are the approximate worst-case heights, and which operation can force many rotations in an AVL tree but not in a red-black tree?
Show answer
The AVL worst case is about 1.44 · log2(1,000,002) − 0.33, roughly 28. The red-black worst case is 2 · log2(1,000,001), roughly 40. Deletion can force up to O(log n) rotations in an AVL tree, one at each level on the path to the root. A red-black tree uses at most 3 rotations per deletion, although recoloring may still travel up the tree.