Lesson 11 · Non-linear structures

AVL Trees

AVL Trees automatically rebalance themselves during insertions and deletions to guarantee logarithmic search times under all conditions.

AVL Trees concept diagramA visual explanation of the layout and operations shown in this lesson.a rotation restores balance when a subtree grows too tallbefore: bf(10) = -2102030rotate left →after: every |bf| ≤ 1201030balance factor = height(left) - height(right); AVL keeps it in {-1, 0, 1}
1

The Balance Factor

An AVL tree — named for Adelson-Velsky and Landis, who described it in 1962 as the first self-balancing binary search tree — is a binary search tree that additionally enforces a height constraint at every node.

Each node's AVL balance factor is height(left subtree) − height(right subtree). The invariant is that this value must be −1, 0, or +1 for every node in the tree. A factor of +2 or −2 anywhere means the tree is out of balance and must be repaired immediately.

Using the convention that an empty subtree has height −1 and a leaf has height 0 makes the arithmetic work without special cases. The code below stores a leaf as 1 and an empty subtree as 0 instead; every difference, and so every balance factor, comes out the same. Mixing the two conventions inside one program is what produces spurious violations.

Each node stores its height (or, in some implementations, just the balance factor) so the value can be computed in O(1) rather than by traversing the subtree. Keeping this field correct after every structural change is where implementation bugs concentrate: a stale height silently disables rebalancing, and the tree degrades without any visible error.

The payoff is a hard guarantee. The invariant bounds the height at 1.44·log₂(n + 2) — at most about 44% taller than a perfectly balanced tree — so search, insert and delete are O(log n) in the worst case, not merely on average. An ordinary BST offers no such promise, and degenerates to O(n) on sorted input.

  • Balance factor = left height − right height, allowed only in {−1, 0, +1}
  • Store the height in each node so the check is O(1)
  • A stale height field disables rebalancing silently
  • Height bounded by 1.44·log₂(n+2), giving worst-case O(log n)
2

The Four Rotation Cases

An AVL rotation is a local rearrangement of two or three nodes that changes the tree's shape while preserving the in-order sequence, and therefore the BST ordering. It is the only repair tool an AVL tree uses, and it runs in O(1).

After an insertion or deletion, walk back up toward the root. At the first node whose balance factor reaches ±2, apply the appropriate rotation. Which one depends on the shape of the path from that node down into the heavier side, giving exactly four cases.

Left-Left (LL): the node is left-heavy and its left child is also left-heavy. One right rotation at the unbalanced node fixes it.

Right-Right (RR): the mirror image — right-heavy with a right-heavy right child. One left rotation.

Left-Right (LR): left-heavy, but the left child is right-heavy. A single rotation does not help, because the offending subtree is on the inside. First rotate the left child left, converting the shape into LL, then rotate the node right. Two rotations.

Right-Left (RL): the mirror — right-heavy with a left-heavy right child. Rotate the right child right, then the node left.

The pattern is worth stating as a rule rather than four memorised diagrams: when the imbalance zigzags, straighten it first. The single rotations handle straight-line imbalances; the double rotations convert a zigzag into a straight line and then apply the single case.

Deletion adds one shape that insertion never creates: the heavy child is itself balanced, with factor 0. Treat it as the straight case (one rotation toward the light side). After that rotation the subtree keeps its height, so the repair stops there. Every rotation must also update the heights of the nodes it moved, from the bottom up, or later balance checks read stale values.

  • Rotations preserve in-order sequence, so the BST ordering survives
  • Straight-line imbalance: one rotation. Zigzag: two
  • Fix the lowest node whose balance factor reaches ±2
  • A balanced heavy child (factor 0) appears only after a delete and takes one rotation
3

Insertion and Deletion Differ

AVL tree insertion proceeds as an ordinary BST insert, placing the new node as a leaf. Then the path back to the root is retraced, updating heights and checking balance factors.

The important property is that one fix is always enough: a single rotation for a straight case, a double rotation for a zigzag. The fix returns the subtree to the height it had before the insertion, so nothing above it can still be unbalanced and the retracing can stop. Insertion therefore costs O(log n) to descend plus O(1) of rebalancing.

AVL tree deletion does not share this property, and the difference is the most commonly missed point about AVL trees. A rotation after a delete may leave the subtree shorter than it was, which can unbalance the node above, which may need its own rotation, and so on.

So deletion may require up to O(log n) rotations — potentially one at every level from the deleted node to the root. The retracing cannot stop at the first fix; it must continue upward until a node's height is unchanged by the repair.

The deletion itself follows the standard BST cases first: a leaf is removed directly, a node with one child is replaced by that child, and a node with two children is replaced by its inorder successor — the leftmost node of the right subtree — which is then deleted from that subtree. Rebalancing begins from the position where a node was physically removed, not from the node whose key was logically deleted.

That distinction causes real bugs: retracing from the wrong starting point skips the nodes whose heights actually changed. Duplicate keys need a fixed rule too: the code sends an equal key to the right, and search, insert and delete must all agree on that side.

  • Insertion needs at most one fix, then retracing can stop
  • Deletion may need a rotation at every level up to the root
  • A rotation after deletion can shorten the subtree, propagating upward
  • Retrace from where a node was physically removed, not logically deleted
Key reference

Terms, operations, and practical uses

Balance Mechanics

  • Balance FactorCalculated as the height of the left subtree minus the height of the right subtree. Must be -1, 0, or 1.
  • Height TrackingEach node actively stores its height, which is updated whenever its children are modified.
  • Imbalance DetectionChecked on the path back to the root after an insertion/deletion. Triggered if a balance factor reaches +2 or -2.

Rotations

  • Right Rotation (LL)Performed when a node is unbalanced due to an insertion in the left child's left subtree. The left child becomes the new root.
  • Left Rotation (RR)Performed when a node is unbalanced due to an insertion in the right child's right subtree.
  • Left-Right Rotation (LR)A double rotation (Left on child, Right on parent) used when the insertion is in the left child's right subtree.

Complexity

  • SearchStrictly O(log N) because the height is mathematically guaranteed to be proportional to log(N).
  • InsertionO(log N) to find the spot and update heights, then one fix of at most two rotations.
  • DeletionO(log N), but unlike insertion, a deletion might trigger O(log N) cascading rotations all the way to the root.
Implementation

Code in Python, C++ and Java

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 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)
    bf = balance(node)
    if bf > 1:
        if balance(node.left) < 0:
            node.left = rotate_left(node.left)
        return rotate_right(node)
    if bf < -1:
        if balance(node.right) > 0:
            node.right = rotate_right(node.right)
        return rotate_left(node)
    return node


def insert(node, key):
    if not node:
        return Node(key)
    if key < node.key:
        node.left = insert(node.left, key)
    else:
        node.right = insert(node.right, key)
    return rebalance(node)


def delete(node, key):
    if not node:
        return None
    if key < node.key:
        node.left = delete(node.left, key)
    elif key > node.key:
        node.right = delete(node.right, key)
    elif not node.left or not node.right:
        return node.left or node.right
    else:
        succ = node.right
        while succ.left:
            succ = succ.left
        node.key = succ.key
        node.right = delete(node.right, succ.key)
    return rebalance(node)


def preorder(node):
    return [node.key] + preorder(node.left) + preorder(node.right) if node else []


root = None
for key in (10, 20, 30, 25, 27):
    root = insert(root, key)
print("after inserts:", *preorder(root))
root = delete(root, 10)
print("after deleting 10:", *preorder(root))
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;

struct Node {
    int key, height = 1;
    Node *left = nullptr, *right = nullptr;
    explicit Node(int k) : key(k) {}
};

int height(Node* node) { return node ? node->height : 0; }

void update(Node* node) { node->height = 1 + max(height(node->left), height(node->right)); }

int balance(Node* node) { return height(node->left) - height(node->right); }

Node* rotateRight(Node* y) {
    Node* x = y->left;
    y->left = x->right;
    x->right = y;
    update(y);
    update(x);
    return x;
}

Node* rotateLeft(Node* x) {
    Node* y = x->right;
    x->right = y->left;
    y->left = x;
    update(x);
    update(y);
    return y;
}

Node* rebalance(Node* node) {
    update(node);
    int bf = balance(node);
    if (bf > 1) {
        if (balance(node->left) < 0) node->left = rotateLeft(node->left);
        return rotateRight(node);
    }
    if (bf < -1) {
        if (balance(node->right) > 0) node->right = rotateRight(node->right);
        return rotateLeft(node);
    }
    return node;
}

Node* insert(Node* node, int key) {
    if (!node) return new Node(key);
    if (key < node->key) node->left = insert(node->left, key);
    else node->right = insert(node->right, key);
    return rebalance(node);
}

Node* remove(Node* node, int key) {
    if (!node) return nullptr;
    if (key < node->key) {
        node->left = remove(node->left, key);
    } else if (key > node->key) {
        node->right = remove(node->right, key);
    } else if (!node->left || !node->right) {
        Node* child = node->left ? node->left : node->right;
        delete node;
        return child;
    } else {
        Node* succ = node->right;
        while (succ->left) succ = succ->left;
        node->key = succ->key;
        node->right = remove(node->right, succ->key);
    }
    return rebalance(node);
}

void preorder(Node* node, vector<int>& out) {
    if (!node) return;
    out.push_back(node->key);
    preorder(node->left, out);
    preorder(node->right, out);
}

void print(const char* label, Node* root) {
    vector<int> keys;
    preorder(root, keys);
    cout << label;
    for (int k : keys) cout << ' ' << k;
    cout << '\n';
}

int main() {
    Node* root = nullptr;
    for (int key : {10, 20, 30, 25, 27}) root = insert(root, key);
    print("after inserts:", root);
    root = remove(root, 10);
    print("after deleting 10:", root);
}
import java.util.ArrayList;
import java.util.List;

public class Main {
    static class Node {
        int key, height = 1;
        Node left, right;

        Node(int key) {
            this.key = key;
        }
    }

    static int height(Node node) {
        return node == null ? 0 : node.height;
    }

    static void update(Node node) {
        node.height = 1 + Math.max(height(node.left), height(node.right));
    }

    static int balance(Node node) {
        return height(node.left) - height(node.right);
    }

    static Node rotateRight(Node y) {
        Node x = y.left;
        y.left = x.right;
        x.right = y;
        update(y);
        update(x);
        return x;
    }

    static Node rotateLeft(Node x) {
        Node y = x.right;
        x.right = y.left;
        y.left = x;
        update(x);
        update(y);
        return y;
    }

    static Node rebalance(Node node) {
        update(node);
        int bf = balance(node);
        if (bf > 1) {
            if (balance(node.left) < 0) node.left = rotateLeft(node.left);
            return rotateRight(node);
        }
        if (bf < -1) {
            if (balance(node.right) > 0) node.right = rotateRight(node.right);
            return rotateLeft(node);
        }
        return node;
    }

    static Node insert(Node node, int key) {
        if (node == null) return new Node(key);
        if (key < node.key) node.left = insert(node.left, key);
        else node.right = insert(node.right, key);
        return rebalance(node);
    }

    static Node delete(Node node, int key) {
        if (node == null) return null;
        if (key < node.key) {
            node.left = delete(node.left, key);
        } else if (key > node.key) {
            node.right = delete(node.right, key);
        } else if (node.left == null || node.right == null) {
            return node.left != null ? node.left : node.right;
        } else {
            Node succ = node.right;
            while (succ.left != null) succ = succ.left;
            node.key = succ.key;
            node.right = delete(node.right, succ.key);
        }
        return rebalance(node);
    }

    static void preorder(Node node, List<Integer> out) {
        if (node == null) return;
        out.add(node.key);
        preorder(node.left, out);
        preorder(node.right, out);
    }

    static void print(String label, Node root) {
        List<Integer> keys = new ArrayList<>();
        preorder(root, keys);
        StringBuilder sb = new StringBuilder(label);
        for (int k : keys) sb.append(' ').append(k);
        System.out.println(sb);
    }

    public static void main(String[] args) {
        Node root = null;
        for (int key : new int[] {10, 20, 30, 25, 27}) root = insert(root, key);
        print("after inserts:", root);
        root = delete(root, 10);
        print("after deleting 10:", root);
    }
}
Watch it run

Step through it

Running on insert 10, 20, 30, 25, 27 into an empty AVL tree, then delete 10

bfbalance factor = left height − right height10010 is the root, balance factor 0
Step 1

Insert 10

The tree is empty, so 10 becomes the root. A single node has two empty subtrees of height −1, so its balance factor is 0.

Output
1 / 14
4

Strict Balance and Its Price

AVL and red-black trees are both self-balancing binary search trees with O(log n) worst-case operations, and choosing between them is an engineering trade rather than one being better. A third option, the splay tree, keeps no balance data at all and moves each accessed node to the root, giving O(log n) amortized rather than worst-case bounds.

AVL is more strictly balanced. Its height bound is 1.44·log₂ n against red-black's 2·log₂ n, so an AVL tree is meaningfully shorter — which means fewer comparisons and fewer cache misses per lookup. For read-heavy workloads, AVL wins.

Red-black rebalances less. Its looser invariant tolerates more imbalance before intervening, and much of its repair work is recolouring — changing a bit — rather than rotating. Insertion needs at most 2 rotations and deletion at most 3, both constant, against AVL's potential O(log n) rotations on deletion. For write-heavy workloads, red-black wins.

This is why standard libraries almost universally choose red-black: std::map and std::set in C++, TreeMap and TreeSet in Java, and the Linux kernel's scheduler and memory management. A general-purpose container cannot assume a read-heavy workload, so the cheaper worst-case modification cost is the safer default.

AVL trees appear where lookups dominate and updates are rare — in-memory database indexes built once and queried repeatedly are the usual example.

There is also a maintenance dimension worth noting: AVL logic is generally considered easier to reason about and to implement correctly, since the four rotation cases are symmetric and the invariant is a simple numeric check. Red-black insertion and deletion involve more cases and are correspondingly more error-prone to write from scratch.

How the two balancing schemes compare
AVLRed-black
Height bound1.44·log₂ n2·log₂ n
Lookup speedFaster — shorter treeSlower
Rotations on insert≤ 2 (one single or double fix)≤ 2
Rotations on deleteO(log n)≤ 3
Best forRead-heavy workloadsGeneral purpose
Used byIn-memory indexesstd::map, TreeMap, Linux kernel
  • AVL is shorter, so lookups are faster
  • Red-black rebalances less, so modifications are cheaper
  • Deletion is the asymmetry: O(log n) rotations against at most 3
  • Libraries default to red-black; AVL suits read-heavy use