Sub topic 15
Keeping a BST balanced: AVL trees
This chapter assumes you know the BST property, search, insertion, and deletion. It also assumes you can reason about tree height and read recursive Python. The previous chapter showed that every BST operation costs O(h), where h is the height. A BST built from sorted input has height n − 1 and degrades to a linked list. An AVL tree is a BST that restores a small height after each update.
The idea: bound the height difference
The balance factor of a node is the height of its left subtree minus the height of its right subtree.
BF(node) = height(node.left) - height(node.right)This chapter uses the convention that an empty tree has height -1 and a leaf has height 0. Other books use 0 and 1, so check the convention in any exam question. The balance factors are the same under both conventions, because the offset cancels in the subtraction.
An AVL tree is a BST in which every node has a balance factor of -1, 0, or +1. Adelson-Velsky and Landis proposed it in 1962. Two points matter:
- The condition applies to every node, not only the root.
- Both subtrees of a node can be tall and still satisfy it, as long as their heights differ by at most 1.
An update can push one node's balance factor to +2 or -2. A rotation is a constant-time local rewiring of pointers that fixes this. It lowers the height of the heavy side and keeps the BST property.
Why the height stays logarithmic
Let N(h) be the minimum number of nodes in an AVL tree of height h. The sparsest AVL tree of height h has a root, one subtree of height h − 1, and one of height h − 2. Both subtrees must themselves be as sparse as possible, so:
N(h) = N(h-1) + N(h-2) + 1, N(0) = 1, N(1) = 2| h | 0 | 1 | 2 | 3 | 4 | 5 | 6 |
|---|---|---|---|---|---|---|---|
| N(h) | 1 | 2 | 4 | 7 | 12 | 20 | 33 |
This is the Fibonacci recurrence plus one. In closed form, N(h) = F(h+3) − 1 with F(1) = F(2) = 1. Fibonacci numbers grow exponentially, so the height is at most about 1.44·log₂(n + 2). The height is also at least ⌊log₂ n⌋, which a perfect or complete tree reaches. Hence h = Θ(log n) in every case, and search, insertion, and deletion are all O(log n) in the worst case.
GATE questions often ask for the maximum height of an AVL tree with n nodes, or the minimum number of nodes for a given height. Use the table above and the recurrence. Check which height convention the question uses. Under the "leaf has height 1" convention, shift every h up by one.
Rotations
A rotation changes the shape of a subtree and leaves its inorder sequence unchanged. The BST property therefore survives.
Right rotation at node y, where x is y's left child:
- x becomes the new subtree root.
- y becomes x's right child.
- x's old right subtree becomes y's left subtree.
A left rotation is the mirror image. Both take O(1) time.
The four imbalance cases
After an insertion, find the lowest node z whose balance factor is +2 or -2. The case depends on where the new key went relative to z.
| Case | BF(z) | BF of heavy child | Fix |
|---|---|---|---|
| Left-Left (LL) | +2 | +1 (or 0 after deletion) | Right rotation at z |
| Left-Right (LR) | +2 | -1 | Left rotation at z.left, then right rotation at z |
| Right-Right (RR) | -2 | -1 (or 0 after deletion) | Left rotation at z |
| Right-Left (RL) | -2 | +1 | Right rotation at z.right, then left rotation at z |
The LR and RL cases need a double rotation. A single rotation would only move the "zig-zag" shape from one side to the other.
Implementation
This code stores each node's height so that balance factors take O(1) time. Duplicate keys are ignored, as in the earlier BST insertion.
class AVLNode:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
self.height = 0
def height(node):
return node.height if node else -1
def update(node):
node.height = 1 + max(height(node.left), height(node.right))
def balance(node):
return height(node.left) - height(node.right)
def rotate_right(y):
x = y.left
y.left = x.right
x.right = y
update(y)
update(x)
return x
def rotate_left(x):
y = x.right
x.right = y.left
y.left = x
update(x)
update(y)
return y
def rebalance(node):
update(node)
b = balance(node)
if b > 1:
if balance(node.left) < 0:
node.left = rotate_left(node.left)
return rotate_right(node)
if b < -1:
if balance(node.right) > 0:
node.right = rotate_right(node.right)
return rotate_left(node)
return node
def insert(node, key):
if node is None:
return AVLNode(key)
if key < node.key:
node.left = insert(node.left, key)
elif key > node.key:
node.right = insert(node.right, key)
else:
return node
return rebalance(node)
def preorder(node, out):
if node:
out.append(node.key)
preorder(node.left, out)
preorder(node.right, out)
root = None
for k in [10, 20, 30, 40, 50, 25]:
root = insert(root, k)
order = []
preorder(root, order)
print(order)
print(root.height)The output is:
[30, 20, 10, 25, 40, 50]
2Each recursive call returns the new root of its subtree. The caller reattaches that root, which is why rotations that change the subtree root work without parent pointers.
Tracing the example
- Inserting 10, 20, 30 makes a right chain. Node 10 has BF -2 and its right child 20 has BF -1, so this is RR. A left rotation gives 20 as root with children 10 and 30.
- Inserting 40 and 50 extends the right side. Node 30 reaches BF -2 with right child 40 at BF -1, so this is RR again. A left rotation at 30 gives the tree 20(10, 40(30, 50)).
- Inserting 25 goes right to 40, then left to 30, then left to 25. Node 20 now has BF -2, and its right child 40 has BF +1. This is RL. Rotate right at 40, which makes 30 the subtree root, then rotate left at 20. The final root is 30 with subtrees 20(10, 25) and 40(-, 50).
Deletion
Deletion works in two steps:
- Delete as in an ordinary BST. A node with two children is replaced by its inorder successor, as in the earlier chapter.
- Walk back up to the root and call
rebalanceon every ancestor.
The code above supports this directly. You would add a delete function that ends with return rebalance(node), the same way insert does.
Deletion differs from insertion in two ways:
- The heavy child can have balance factor 0, which only deletion can produce at this point. For BF(z) = +2 and BF(z.left) = 0, a single right rotation is correct. The
rebalancefunction above handles this, because it uses a double rotation only when the child's balance factor has the opposite sign. - A rotation can reduce the subtree's height, which can unbalance an ancestor. Deletion may therefore need a rotation at several levels, up to O(log n) in total. Insertion never needs more than one rotation, either single or double.
Complexity summary
| Operation | Plain BST (worst) | AVL tree (worst) |
|---|---|---|
| Search | O(n) | O(log n) |
| Insert | O(n) | O(log n) |
| Delete | O(n) | O(log n) |
| Rotations per insert | none | at most 1 (single or double) |
| Rotations per delete | none | up to O(log n) |
Building an AVL tree from n keys by repeated insertion takes O(n log n). Inorder traversal still yields sorted keys, because rotations preserve inorder order.
Common errors
- Checking only the root. A tree whose root has BF 0 can still violate the AVL condition lower down.
- Rebalancing at the wrong node. The node to fix is the lowest unbalanced ancestor of the changed position. Fixing a higher one first gives wrong shapes.
- Using a single rotation for a zig-zag. If the heavy child leans the opposite way from the imbalance, a single rotation leaves the tree unbalanced.
- Not updating heights after rotating. Update the lower node first, then the new subtree root, as
rotate_rightandrotate_leftdo. - Mixing height conventions. Heights of 0 or 1 for a leaf change the answers to "minimum nodes for height h" questions.
Exercise
Starting from an empty AVL tree, insert 30, 20, 10, 25, 28 in that order. Give the preorder traversal of the final tree. Name each rotation case that occurs.
Show answer
Inserting 30, 20, 10 creates a left chain. This is an LL case at 30, and a right rotation gives 20(10, 30). Inserting 25 puts it as the left child of 30, which is balanced. Inserting 28 goes 20 → 30 → 25 → right child of 25. Node 30 has BF +2 and its left child 25 has BF -1, so this is an LR case. Rotate left at 25, which makes 28 the left child of 30 with 25 as its left child, then rotate right at 30. The subtree becomes 28(25, 30). The final tree is 20(10, 28(25, 30)). Its preorder traversal is 20, 10, 28, 25, 30.
Exercise
What is the minimum number of nodes in an AVL tree of height 6, where a single node has height 0? What is the maximum possible height of an AVL tree with 20 nodes?
Show answer
Use N(h) = N(h-1) + N(h-2) + 1 with N(0) = 1 and N(1) = 2. This gives N(2) = 4, N(3) = 7, N(4) = 12, N(5) = 20, and N(6) = 33. So the minimum is 33 nodes. Since N(5) = 20, a tree of 20 nodes can have height 5. Height 6 needs at least 33 nodes, so the maximum height with 20 nodes is 5.
Exercise
An AVL tree has a node z with BF(z) = +2, and its left child has BF 0. Which operation could produce this situation, and which rotation fixes it?
Show answer
This can only arise after a deletion, because a left child with BF 0 cannot be the direct result of an insertion that unbalanced z. It is treated as an LL case. A single right rotation at z restores balance. A double rotation is wrong here.