Essential Data Structures home
AVL Tree
A binary search tree that watches its own balance and fixes itself after every insert and delete, so it can never degenerate into a slow line.
What it is
An AVL tree is a binary search tree with one extra rule: at every node, the heights of the left and right subtrees may differ by at most one. That difference is called the balance factor, and it is always -1, 0, or 1 in a healthy AVL tree. The name comes from its inventors, Adelson-Velsky and Landis, who published the idea in 1962, the first self-balancing search tree.
The rule is what fixes the plain binary search tree's weakness. A plain tree fed values in sorted order degenerates into a linked list, and every operation slows to a scan. An AVL tree never lets that happen. Because the height of a tree with n nodes is kept at O(log n), search, insert, and delete all stay logarithmic, no matter the order values arrive in.
Each node stores its height, so the balance factor can be checked in constant time. The tree pays for that guarantee with a little extra work on insert and delete: after changing the tree, it walks back up and restores the balance where it was broken.
How it works
Insert works like an ordinary binary search tree insert: walk down comparing values until you find an empty spot, and put the new node there. Then walk back up the path, updating heights and checking balance factors. If a node is out of balance, a rotation fixes it.
A rotation is a small local rearrangement that keeps the tree ordered while making a tall side shorter. There are four cases. When the left child is too tall and its left child is tall too, one right rotation (the LL case) fixes it. The mirror image, the RR case, needs one left rotation. When the imbalance runs in a zigzag, the LR and RL cases, a double rotation is needed: rotate the child first, then the node. An insertion needs at most one single or double rotation. A deletion can need several rotations on the way back up, but still at most one per level.
Delete works the same way as in a plain binary search tree: remove the node, replace it with its successor when it has two children, then walk back up, updating heights and rotating wherever the balance factor has drifted outside -1 to 1. Search, minimum, and maximum are unchanged from a plain binary search tree, and they are fast precisely because the height is guaranteed small.
Complexity
| Operation | Average | Worst case |
|---|---|---|
| Search | O(log n) | O(log n) |
| Insert | O(log n) | O(log n) |
| Delete | O(log n) | O(log n) |
| Minimum / maximum | O(log n) | O(log n) |
| In-order traversal | O(n) | O(n) |
n is the number of items. The worst case column is O(log n) for search, insert, and delete because the balance rule keeps the height at about 1.44 log2 n, so the tree can never degenerate into a line the way a plain binary search tree can.
When to use it, and when not to
Use an AVL tree when you need ordered data with guaranteed fast lookup, and the data arrives in an order you do not control. It is the stricter cousin of the red-black tree: it stays more tightly balanced, so lookups are slightly faster, which makes it a good fit for read-heavy workloads where searches far outnumber inserts and deletes.
Do not use an AVL tree when the data is unordered and you only need fast lookup by key, because a hash table is faster there, with O(1) average lookup and no ordering cost. Do not use it when insertions dominate and you rarely search, because each insert pays the rotation cost to stay balanced; a plain structure or a red-black tree, which rebalances less often, may be cheaper. Python's built-in dict and set are hash tables, not trees, and Python has no built-in AVL tree.
Where you meet it
AVL trees are the textbook self-balancing tree, so they show up in classrooms and interviews more than in production code, but the idea runs real systems. Database indexes and in-memory ordered maps use the same balancing principle, in B-tree or red-black form, to guarantee that lookups stay fast as data grows. Any system that must keep sorted data searchable after arbitrary inserts, such as a file system's directory index or a router's forwarding table, leans on a self-balancing tree, and the AVL tree is the simplest version of that guarantee.
In Python
class Node:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
self.height = 1
def height(node):
return node.height if node else 0
def balance(node):
return height(node.left) - height(node.right) if node else 0
def rotate_right(y):
x, t = y.left, y.left.right
x.right, y.left = y, t
y.height = 1 + max(height(y.left), height(y.right))
x.height = 1 + max(height(x.left), height(x.right))
return x
def rotate_left(x):
y, t = x.right, x.right.left
y.left, x.right = x, t
x.height = 1 + max(height(x.left), height(x.right))
y.height = 1 + max(height(y.left), height(y.right))
return y
def insert(node, value):
if node is None:
return Node(value)
if value < node.value:
node.left = insert(node.left, value)
elif value > node.value:
node.right = insert(node.right, value)
else:
return node
node.height = 1 + max(height(node.left), height(node.right))
b = balance(node)
if b > 1 and value < node.left.value: # LL
return rotate_right(node)
if b < -1 and value > node.right.value: # RR
return rotate_left(node)
if b > 1 and value > node.left.value: # LR
node.left = rotate_left(node.left)
return rotate_right(node)
if b < -1 and value < node.right.value: # RL
node.right = rotate_right(node.right)
return rotate_left(node)
return node
def inorder(node, out):
if node is not None:
inorder(node.left, out)
out.append(node.value)
inorder(node.right, out)
root = None
for v in [30, 20, 40, 10, 25, 35, 50]:
root = insert(root, v)
out = []
inorder(root, out)
print(out) # [10, 20, 25, 30, 35, 40, 50]
print(root.height) # 3
print(balance(root)) # 0
# Insert in sorted order: a plain BST would become a line.
root2 = None
for v in [10, 20, 30, 40, 50]:
root2 = insert(root2, v)
print(root2.height) # 3, still balanced
In short: an AVL tree is a binary search tree with a balance rule enforced at every node, so its height stays logarithmic and search, insert, and delete are O(log n) even in the worst case. Rotations are the mechanism, a small local fix that keeps the tree ordered while cutting a tall side down.
Sources
- AVL tree, Wikipedia
- Python docs, Data Structures tutorial
- Cormen, Leiserson, Rivest, and Stein, Introduction to Algorithms, chapter 13