AVL Trees: A Hands-On Guide to Rotations
Learn AVL insertions and deletions through height and balance-factor traces, then use a compact Python implementation and compare tree choices.
AVL trees keep every node within one level of height balance. This guide traces all four insertion rotations, shows a deletion that triggers rebalancing, and includes a small Python implementation to run.
AVL Trees: A Hands-On Guide to Rotations
An AVL tree is a binary search tree that keeps the heights of each node’s left and right subtrees within one of each other. That rule keeps search, insertion, and deletion at O(log n), even when keys arrive in an awkward order.
This guide is for readers who know loops, functions, and basic binary search trees. We’ll use Python 3 and track height at each step. If the BST ordering rule needs a refresher, start with the binary tree and BST guide.
One height convention
Use the same convention for every example:
- An empty child has height 0.
- A leaf has height 1.
height(node) = 1 + max(height(left), height(right)).BF(node) = height(left) − height(right).- A node is balanced when its balance factor is −1, 0, or +1.
In the diagrams, 20[h=2, BF=0] means key 20 has height 2 and balance factor 0. A missing child is written as a dot. Positive balance means left-heavy; negative balance means right-heavy.
Insertion: follow the taller path
Each trace starts with an empty tree. After inserting a key, walk back toward the root, updating heights. The first node with |BF| > 1 is the point to rebalance.
LL: one right rotation
Insert 30, 20, 10.
After 30:
30[h=1, BF=0]
After 20:
30[h=2, BF=+1]
└─L 20[h=1, BF=0]
After 10, before rotation:
30[h=3, BF=+2]
└─L 20[h=2, BF=+1]
└─L 10[h=1, BF=0]
The new key extended the left side of the left child. Rotate right at 30:
20[h=2, BF=0]
├─L 10[h=1, BF=0]
└─R 30[h=1, BF=0]
RR: one left rotation
Insert 10, 20, 30.
Before rotation:
10[h=3, BF=-2]
└─R 20[h=2, BF=-1]
└─R 30[h=1, BF=0]
The new key extended the right side of the right child. Rotate left at 10:
20[h=2, BF=0]
├─L 10[h=1, BF=0]
└─R 30[h=1, BF=0]
LR: rotate the child, then the node
Insert 30, 10, 20.
Before rotation:
30[h=3, BF=+2]
└─L 10[h=2, BF=-1]
└─R 20[h=1, BF=0]
First rotate left at 10:
30[h=3, BF=+2]
└─L 20[h=2, BF=+1]
└─L 10[h=1, BF=0]
Then rotate right at 30:
20[h=2, BF=0]
├─L 10[h=1, BF=0]
└─R 30[h=1, BF=0]
RL: rotate the child, then the node
Insert 10, 30, 20.
Before rotation:
10[h=3, BF=-2]
└─R 30[h=2, BF=+1]
└─L 20[h=1, BF=0]
First rotate right at 30:
10[h=3, BF=-2]
└─R 20[h=2, BF=-1]
└─R 30[h=1, BF=0]
Then rotate left at 10:
20[h=2, BF=0]
├─L 10[h=1, BF=0]
└─R 30[h=1, BF=0]
The two-letter names describe the heavy path: LL and RR need one rotation; LR and RL need two. When insertion makes a subtree unbalanced, the first repaired ancestor returns to its earlier height, so insertion does not need further rotations above that point.
Deletion: rebalance on the way back up
Deletion can shorten a subtree. That change travels up the search path and can make an ancestor unbalanced.
Continue from the LL example’s balanced tree, then insert 40. The tree is:
20[h=3, BF=-1]
├─L 10[h=1, BF=0]
└─R 30[h=2, BF=-1]
└─R 40[h=1, BF=0]
Delete 10. Before rebalancing, the root’s left height is 0 and its right height is 2:
20[h=3, BF=-2]
└─R 30[h=2, BF=-1]
└─R 40[h=1, BF=0]
This is an RR case at 20. Rotate left:
30[h=2, BF=0]
├─L 20[h=1, BF=0]
└─R 40[h=1, BF=0]
The height and balance updates continue from the deleted node toward the root. Unlike insertion, deletion can reduce the repaired subtree’s height, so a higher ancestor may need another rotation.
A small Python implementation
The implementation stores each node’s height and computes its balance factor when needed. Duplicate keys are ignored; deleting a missing key leaves the tree unchanged.
class Node:
def __init__(self, key):
self.key = key
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 update(node):
node.height = 1 + max(height(node.left), height(node.right))
def rotate_right(root):
pivot = root.left
middle = pivot.right
pivot.right = root
root.left = middle
update(root)
update(pivot)
return pivot
def rotate_left(root):
pivot = root.right
middle = pivot.left
pivot.left = root
root.right = middle
update(root)
update(pivot)
return pivot
def rebalance(node):
update(node)
factor = balance(node)
if factor > 1:
if balance(node.left) < 0:
node.left = rotate_left(node.left)
return rotate_right(node)
if factor < -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 Node(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 smallest(node):
while node.left:
node = node.left
return node
def delete(node, key):
if node is None:
return None
if key < node.key:
node.left = delete(node.left, key)
elif key > node.key:
node.right = delete(node.right, key)
elif node.left is None:
return node.right
elif node.right is None:
return node.left
else:
successor = smallest(node.right)
node.key = successor.key
node.right = delete(node.right, successor.key)
return rebalance(node)
def show(node):
if node is None:
return "."
return (
f"{node.key}[h={node.height}, BF={balance(node):+d}]"
f"({show(node.left)},{show(node.right)})"
)
cases = {
"LL": [30, 20, 10],
"RR": [10, 20, 30],
"LR": [30, 10, 20],
"RL": [10, 30, 20],
}
for name, keys in cases.items():
root = None
for key in keys:
root = insert(root, key)
print(name, show(root))
root = None
for key in [30, 20, 10, 40]:
root = insert(root, key)
print("before delete", show(root))
root = delete(root, 10)
print("after delete", show(root))
Expected output:
LL 20[h=2, BF=+0](10[h=1, BF=+0](.,.),30[h=1, BF=+0](.,.))
RR 20[h=2, BF=+0](10[h=1, BF=+0](.,.),30[h=1, BF=+0](.,.))
LR 20[h=2, BF=+0](10[h=1, BF=+0](.,.),30[h=1, BF=+0](.,.))
RL 20[h=2, BF=+0](10[h=1, BF=+0](.,.),30[h=1, BF=+0](.,.))
before delete 20[h=3, BF=-1](10[h=1, BF=+0](.,.),30[h=2, BF=-1](.,40[h=1, BF=+0](.,.)))
after delete 30[h=2, BF=+0](20[h=1, BF=+0](.,.),40[h=1, BF=+0](.,.))
This compact representation makes it easier to check height updates than to inspect pointer changes. The rotation traces above show the intermediate shapes the output alone hides.
Exercises
- Insert
[40, 20, 30]. Which case is it, and what tree shouldshow(root)return? Expected: root 30 with children 20 and 40; all three nodes have height 1 except the root, whose height is 2 and balance factor is 0. - Build the tree from
[30, 20, 10, 40], then delete 10. Expected: theafter deleteline shown above, with root 30.
Choosing between AVL and red-black trees
AVL and red-black trees both keep search, insertion, and deletion logarithmic. AVL’s stricter height rule can suit workloads that search often; red-black trees allow looser balance and may do less rebalancing work on updates. Those are workload considerations, not a universal speed ranking. See the red-black tree guide for its balancing rules and comparison.
Further reading
- NIST Dictionary of Algorithms and Data Structures: AVL tree defines the AVL balance condition and logarithmic operation bounds.
- Princeton’s AVL symbol-table implementation shows height updates and rotations in code.
- Binary trees and binary search trees reviews the ordering property used here.
Category
Related Posts
Red-Black Trees: Balanced Search Trees with Simpler Rotations
Master red-black tree properties, insertion fixup cases, and color flip mechanics. Learn when RB trees outperform AVL and when they don't.
Bellman-Ford Algorithm: Shortest Paths with Negative Weights
Learn the Bellman-Ford algorithm for single-source shortest paths including negative edge weights and negative cycle detection.
Binary Trees and Binary Search Trees: Hierarchical Data
Master tree traversal (inorder, preorder, postorder), BST operations, and when trees outperform other data structures.