AVL Tree in Data Structure with Example
An AVL Tree (named after inventors Adelson-Velsky and Landis) is a self-balancing Binary Search Tree in which the height difference between the left and right subtrees of every node — called the balance factor — is at most 1.
Balance Factor
Balance Factor = height(left subtree) − height(right subtree). It must be -1, 0, or 1 for every node. If an insertion or deletion violates this, the tree performs rotations to restore balance.
Rotations
- Left Rotation: used when a node is right-heavy.
- Right Rotation: used when a node is left-heavy.
- Left-Right Rotation: a left rotation followed by a right rotation.
- Right-Left Rotation: a right rotation followed by a left rotation.
Worked Example
Inserting 10, 20, 30 in that order into an empty AVL tree causes a right-heavy imbalance at node 10 after inserting 30 (a 'Left-Left' case from the perspective of node 10 being unbalanced due to its right-right chain). The tree performs a single left rotation, making 20 the new root with 10 as its left child and 30 as its right child, restoring balance.
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 right_rotate(y):
x = y.left
T2 = x.right
x.right = y
y.left = T2
y.height = 1 + max(height(y.left), height(y.right))
x.height = 1 + max(height(x.left), height(x.right))
return x
def left_rotate(x):
y = x.right
T2 = y.left
y.left = x
x.right = T2
x.height = 1 + max(height(x.left), height(x.right))
y.height = 1 + max(height(y.left), height(y.right))
return y
Complexity
| Operation | Time |
|---|---|
| Search/Insert/Delete | O(log n) |
Applications
- Databases and file systems requiring guaranteed logarithmic lookup time.
- In-memory indexing structures.
- Situations with frequent insertions/deletions where balance must be maintained.
Spotting Which of the Four Cases You Are In
After an insertion, walk back up from the new node and recompute heights. The first node whose balance factor becomes +2 or -2 is where the fix happens. Its own balance factor, plus that of the child on the heavy side, tells you which rotation to use.
| Case | Unbalanced node | Heavy child | Fix |
|---|---|---|---|
| Left-Left (LL) | +2 | left child is +1 or 0 | Single right rotation |
| Right-Right (RR) | -2 | right child is -1 or 0 | Single left rotation |
| Left-Right (LR) | +2 | left child is -1 | Left rotate the child, then right rotate the node |
| Right-Left (RL) | -2 | right child is +1 | Right rotate the child, then left rotate the node |
The 10, 20, 30 sequence shown above is what most textbooks name the Right-Right case: the imbalance sits on the right of the right child, so one left rotation is enough.
Full Insert Function Using the Rotations
The rotation helpers already defined can be plugged into a standard recursive insert. The function returns the new root of each subtree, which lets a rotation replace the old subtree root cleanly.
def get_balance(node):
return height(node.left) - height(node.right) if node else 0
def insert(root, key):
if not root:
return Node(key)
if key < root.key:
root.left = insert(root.left, key)
elif key > root.key:
root.right = insert(root.right, key)
else:
return root # ignore duplicates
root.height = 1 + max(height(root.left), height(root.right))
balance = get_balance(root)
if balance > 1 and key < root.left.key: # LL
return right_rotate(root)
if balance < -1 and key > root.right.key: # RR
return left_rotate(root)
if balance > 1 and key > root.left.key: # LR
root.left = left_rotate(root.left)
return right_rotate(root)
if balance < -1 and key < root.right.key: # RL
root.right = right_rotate(root.right)
return left_rotate(root)
return root
root = None
for k in [30, 10, 20]:
root = insert(root, k)
print(root.key) # 20
Worked double rotation: inserting 30, 10, 20
After 30 and 10, node 30 has a left child and the tree is fine. Inserting 20 puts it as the right child of 10. Now node 30 has balance +2 while its left child 10 has balance -1, so this is the Left-Right case. A left rotation on 10 lifts 20 above 10, giving a straight left chain 30, 20, 10. A right rotation on 30 then makes 20 the root with 10 on the left and 30 on the right.
AVL Tree or Red-Black Tree?
Both keep operations logarithmic, but they trade off differently. AVL trees are more tightly balanced, so lookups touch fewer levels. Red-black trees allow a looser shape, so inserts and deletes usually need fewer rotations. Libraries such as Java's TreeMap use red-black trees because general-purpose maps see many updates. Pick AVL when reads clearly dominate writes, such as a lookup table built once and queried often.
Bugs to Watch For When Coding It
- Updating the parent's height before the child's height after a rotation. The lower node must be recalculated first.
- Forgetting to assign the returned root, as in calling
insert(root, k)withoutroot =. - Using the wrong direction for the first rotation in LR and RL cases.
- Skipping rebalancing on deletion. Removing a node can unbalance several ancestors, not just one.
To test your code, insert keys 1 to 15 in ascending order. A correct AVL tree ends up perfectly balanced with 8 at the root and a height of 4.