AVL tree

On this page 7

An AVL tree is a self-balancing binary search tree in which the heights of the left and right subtrees of every node differ by at most one. Among data structures in programming, it was the first balanced search tree to be published, introduced in 1962 by Georgy Adelson-Velsky and Evgenii Landis, whose initials give the structure its name.

By restoring balance with rotations after every insertion and deletion, an AVL tree guarantees that search, insert and delete all run in O(log n) time in the worst case. This prevents the degeneration into a linked-list shape that an unbalanced binary search tree suffers when keys arrive in sorted order.

How the AVL balance condition works

The AVL property is defined through the balance factor, which is the height of a node’s right subtree minus the height of its left subtree (some texts use the opposite sign). A tree is a valid AVL tree when every node has a balance factor of -1, 0 or +1.

Each node stores either its height or its balance factor so that the condition can be checked in constant time. After a structural change, the algorithm walks back up from the modified node toward the root, updates the stored values and repairs the first node whose balance factor reaches +2 or -2.

Balance factorMeaningAction required
-1Left subtree one level tallerNone
0Both subtrees equally tallNone
+1Right subtree one level tallerNone
-2Left side too tallRight rotation or left-right rotation
+2Right side too tallLeft rotation or right-left rotation
Balance factor values and their meaning

The strict condition bounds the height tightly. An AVL tree with n nodes has a height of at most about 1.44 log2(n + 2), a result that follows from the fact that the minimum number of nodes for a given height grows like the Fibonacci sequence. In practice, AVL trees are typically within a few percent of a perfectly balanced tree.

Rotations that restore AVL balance

A rotation is a local restructuring of three nodes and their subtrees that changes heights while preserving the in-order sequence of keys. Because only a constant number of pointers change, each rotation costs O(1) time.

Which rotation applies depends on where the excess height lies relative to the unbalanced node. The four imbalance cases are named after the path from that node to the taller grandchild.

CaseCauseFix
Left-leftTaller subtree is the left child’s left sideSingle right rotation
Right-rightTaller subtree is the right child’s right sideSingle left rotation
Left-rightTaller subtree is the left child’s right sideLeft rotation on child, then right rotation
Right-leftTaller subtree is the right child’s left sideRight rotation on child, then left rotation
The four AVL imbalance cases

After an insertion, at most one single or double rotation is needed, because the rotation restores the subtree to its previous height. After a deletion, the subtree may become shorter even after repair, so rotations can propagate and up to O(log n) rotations may be required along the path to the root.

Operations and their cost in an AVL tree

All dictionary operations on an AVL tree run in logarithmic time because each one follows a single root-to-leaf path whose length is bounded by the tree height. The table summarizes the costs.

OperationWorst-case timeNotes
SearchO(log n)Standard binary search tree lookup
InsertO(log n)At most one single or double rotation
DeleteO(log n)Possibly several rotations upward
Minimum or maximumO(log n)Follow leftmost or rightmost path
In-order traversalO(n)Returns keys in sorted order
SpaceO(n)Plus a height or balance field per node
Time and space complexity of AVL tree operations

Because keys remain ordered, an AVL tree also supports range queries, predecessor and successor lookups, and, if each node stores its subtree size, order statistics such as finding the k-th smallest key in logarithmic time.

AVL tree compared with other balanced structures

The AVL tree is usually compared with the red-black tree, the other classic self-balancing binary search tree. AVL trees are more rigidly balanced, which makes lookups slightly faster, while red-black trees tolerate more imbalance and therefore perform fewer rotations on updates.

StructureMaximum heightRebalancing costBest suited for
AVL treeAbout 1.44 log2 nMore rotations on deleteRead-heavy workloads
Red-black treeAbout 2 log2 nFewer rotations, color flipsMixed or write-heavy workloads
Plain binary search treeUp to nNoneRandom keys, simple code
Skip listProbabilistic O(log n)Random level selectionConcurrent implementations
B-treeVery low, high fan-outNode splits and mergesDisk and database indexes
AVL trees and related ordered structures

Many standard libraries, such as the ordered map containers of C++ and Java, use red-black trees because their update cost is more predictable. AVL trees remain common in in-memory lookup tables, databases of read-mostly records and teaching, where the strict balance rule is easy to reason about. Unlike a hash table, both structures keep keys sorted, which matters when ordered iteration is required.

Implementation pitfalls and limitations

Most AVL tree bugs come from forgetting to update stored heights in the correct order after a rotation. The lower node must be recomputed before its new parent, otherwise the parent uses a stale value and later balance decisions go wrong.

  • Choosing the wrong case: the double rotation is needed when the child’s balance factor has the opposite sign to the parent’s; treating it as a single case leaves the tree unbalanced.
  • Stopping too early on deletion: unlike insertion, deletion must continue checking ancestors after a rotation.
  • Recursion depth: recursive implementations are safe because the height is logarithmic, but they still cost more stack frames than iterative versions.
  • Pointer-heavy layout: each node holds two child pointers and often a parent pointer, which hurts cache locality compared with arrays or B-trees.

For workloads dominated by insertions and deletions, or for data stored on disk, an AVL tree is often not the most efficient choice, and a red-black tree or B-tree is preferable.

Understanding it simply

An AVL tree is a way of storing sorted items so that any item can be found quickly, even in a very large collection. Each item points to a smaller one on the left and a larger one on the right, so searching means making a short series of left-or-right choices.

The trick is that the tree keeps itself evenly shaped. Whenever one side grows too tall, it shifts a few items around, like rebalancing a mobile hanging from the ceiling, so that no path becomes long. With a million items, a search needs only about twenty to thirty steps.

Applied in practice

A developer builds an in-memory price index for a trading simulator used in a university finance course. The index holds about 500,000 instrument records keyed by symbol, receives thousands of lookups per second, and changes only when instruments are added or delisted a few times a day.

An earlier version used a plain binary search tree, and because the records were loaded from an alphabetically sorted file, the tree degenerated into a chain and some lookups took hundreds of thousands of comparisons. Replacing it with an AVL tree kept the height below about 27 levels, so every lookup finished in a few microseconds. The sorted structure also allowed the simulator to list all symbols in a given alphabetical range without a separate sort, which a hash table could not offer.