Notes
All notes

AVL Trees and Balanced Trees (DSA #12)

Insert 1, 2, 3, 4, 5 into a plain binary search tree and you get a linked list — height \(n\), search \(O(n)\). The data was already sorted, which is exactly the worst case. A self-balancing tree fixes this by restoring balance after every change, guaranteeing height \(O(\log n)\) no matter the insertion order. The AVL tree is the cleanest example: one simple rule, four rotations, and a hard guarantee.

This chapter covers the balance condition, the four rotation cases, insertion with rebalancing, and how AVL compares with red-black trees and B-trees.

The balance condition

An AVL tree requires that, for every node, the heights of its left and right subtrees differ by at most one. Define the balance factor:

\[ BF(\text{node}) = \text{height}(\text{left}) - \text{height}(\text{right}) \in \{-1, 0, +1\} \]

If any node violates this after an insert or delete, rotations restore it. The payoff: an AVL tree with \(n\) nodes has height at most about \(1.44 \log_2 n\), so search, insert, and delete are all \(O(\log n)\) worst case.

class Node:
    def __init__(self, val):
        self.val, self.left, self.right, self.height = val, None, None, 1

def height(n):
    return n.height if n else 0

def balance(n):
    return height(n.left) - height(n.right) if n else 0

We cache height on each node so the balance factor is \(O(1)\).

Rotations: the four cases

A rotation is a local pointer surgery that reduces height while preserving the BST order. There are two primitives — right rotation and left rotation — and four cases depending on where the imbalance is.

Right rotation (LL case). The left child becomes the new root; the old root becomes its right child.

def rotate_right(y):
    x = y.left
    y.left = x.right
    x.right = y
    y.height = 1 + max(height(y.left), height(y.right))
    x.height = 1 + max(height(x.left), height(x.right))
    return x          # new subtree root

Left rotation (RR case). The mirror image.

def rotate_left(x):
    y = x.right
    x.right = y.left
    y.left = x
    x.height = 1 + max(height(x.left), height(x.right))
    y.height = 1 + max(height(y.left), height(y.right))
    return y
\begin{tikzpicture}[font=\rmfamily, >=stealth,
  n/.style={draw, thick, circle, minimum size=0.6cm, font=\small\bfseries, inner sep=0pt},
  a/.style={->, thick}]
  % before
  \node[n, fill=red!18] (y) at (0,0) {30};
  \node[n, fill=green!22] (x) at (-1.1,-1.0) {20};
  \node[n, fill=blue!12] (t) at (1.1,-1.0) {40};
  \node[n, fill=green!22] (z) at (-1.8,-2.0) {10};
  \node[n, fill=blue!12] (m) at (-0.4,-2.0) {25};
  \draw[a] (y) -- (x); \draw[a] (y) -- (t);
  \draw[a] (x) -- (z); \draw[a] (x) -- (m);
  \node[font=\scriptsize, anchor=north] at (0,-2.5) {before: BF(30)=2};
  % after
  \node[n, fill=green!22] (x2) at (4.2,0) {20};
  \node[n, fill=green!22] (z2) at (3.3,-1.0) {10};
  \node[n, fill=red!18] (y2) at (5.2,-1.0) {30};
  \node[n, fill=blue!12] (m2) at (4.6,-2.0) {25};
  \node[n, fill=blue!12] (t2) at (5.8,-2.0) {40};
  \draw[a] (x2) -- (z2); \draw[a] (x2) -- (y2);
  \draw[a] (y2) -- (m2); \draw[a] (y2) -- (t2);
  \node[font=\scriptsize, anchor=north] at (4.6,-2.5) {after right rotation: balanced};
  \draw[->, very thick] (1.6,-1.0) -- (2.9,-1.0);
\end{tikzpicture}

The other two cases are double rotations:

Insert with rebalancing

Insert exactly as in a BST, then update heights and rebalance on the way back up the recursion.

def insert(node, val):
    if not node:
        return Node(val)
    if val < node.val:
        node.left = insert(node.left, val)
    elif val > node.val:
        node.right = insert(node.right, val)
    else:
        return node                       # no duplicates

    node.height = 1 + max(height(node.left), height(node.right))
    bf = balance(node)

    if bf > 1 and val < node.left.val:    # LL
        return rotate_right(node)
    if bf < -1 and val > node.right.val:  # RR
        return rotate_left(node)
    if bf > 1 and val > node.left.val:    # LR
        node.left = rotate_left(node.left)
        return rotate_right(node)
    if bf < -1 and val < node.right.val:  # RL
        node.right = rotate_right(node.right)
        return rotate_left(node)
    return node

The four if blocks are the four cases. Because a single insert changes height by at most one and only along the root-to-leaf path, one rotation (or double rotation) suffices to restore the whole tree.

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  n/.style={draw, thick, circle, minimum size=0.6cm, font=\small\bfseries, inner sep=0pt},
  a/.style={->, thick}]
  \node[n, fill=red!18] (a) at (0,0) {30};
  \node[n, fill=blue!12] (b) at (-1.0,-0.9) {10};
  \node[n, fill=blue!12] (c) at (1.0,-0.9) {40};
  \node[n, fill=orange!25] (d) at (-1.6,-1.8) {20};
  \draw[a] (a) -- (b); \draw[a] (a) -- (c); \draw[a] (b) -- (d);
  \node[font=\small, anchor=west, text=black!70] at (1.6,-0.4) {case LR:};
  \node[font=\small, anchor=west, text=black!70] at (1.6,-0.9) {left-rotate 10,};
  \node[font=\small, anchor=west, text=black!70] at (1.6,-1.4) {then right-rotate 30};
\end{tikzpicture}

Delete

Deletion begins like the BST delete (Chapter 10) and then rebalances on the way up. Unlike insert, a delete may require multiple rotations up the path, because removing a node can unbalance several ancestors. The code mirrors insert but re-checks balance at every return.

AVL vs other balanced trees

Tree Balance strictness Rebalance cost Use
AVL strict (BF ∈ {-1,0,1}) more rotations lookup-heavy
Red-black looser fewer rotations insert/delete-heavy, stdlib maps
B-tree / B+ multi-way splits/merges disk/database (Chapter 13)

AVL trees are more rigidly balanced, so lookups are a little faster, but inserts and deletes rotate more. Red-black trees trade a taller tree for cheaper updates, which is why most standard-library ordered maps use them. For data on disk, multi-way B-trees win because they minimize disk seeks (Chapter 13).

Pitfalls

QQuestionSelf-check

What is the AVL balance factor, and what are the four rotation cases? Why do red-black trees sometimes beat AVL in practice?

ASolution

The balance factor is height(left) - height(right) and must stay in \(\{-1, 0, +1\}\). The cases are LL (right rotation), RR (left rotation), LR (left then right), and RL (right then left). Red-black trees rebalance with fewer rotations on insert/delete, so they win when updates are frequent, while AVL’s stricter balance helps lookup-heavy workloads.

Next: B-Trees, 2-3 Trees and B+ Trees (DSA #13) — balancing for disks, where a seek costs a hundred thousand CPU cycles.