Abstract flowing gradient in deep indigo and blue tones, smooth and luminous, evoking a modern digital learning atmosphere

Computer Science and programming articles. We do not sell courses.

Building a self-balancing AVL tree in Python

A binary search tree is the workhorse of in-memory indexing: smaller keys go left, larger keys go right, and every comparison discards half the remaining candidates. The catch is that the tree stays quick only while it stays short, and ordinary insertion order gives no promise that it will. Learn more about Helloml.org.

Feed a plain binary search tree a sorted stream — daily transaction timestamps arriving from a Sydney payments processor, or member numbers exported from a membership database — and it flattens into a linked list wearing a costume. Searches that should take a dozen steps now take a few dozen or a few thousand. The AVL tree, named for Adelson, Velsky and Landis, prevents that drift by rotating subtrees whenever the two sides stop matching in height. Learn more about A Guide To The Comb Sort Algorithm And Its Gap Sequence.

The implementation below is plain Python with no third-party packages: a node class, a balance factor, single left and right rotations, double rotations for the zig-zag shapes, insertion, deletion, and a small test suite. Read it in order, because each piece leans on the previous one.

Why a binary search tree can go wrong

The binary search tree invariant is simple: everything in a node's left subtree is smaller, everything in the right subtree is larger, and each level roughly halves the key space. Height, not node count, determines search cost. Insert 1 through 7 in order into an unbalanced tree and you get a staircase with seven levels, so finding 7 takes seven comparisons instead of three.

An AVL tree adds one rule: after every insertion or deletion, the heights of the two subtrees of any node may differ by at most one. That constraint keeps the height near 1.44 log₂(n + 2) − 0.33, so lookups, insertions and deletions stay O(log n) in the worst case rather than merely on average. The price is a little bookkeeping after each update, paid for with a constant-time rotation.

That predictability is why teams reach for the structure where latency matters: a Melbourne fintech indexing superannuation contributions, an operations platform reconciling overnight batches, or a catalogue that must answer range queries between two account dates. Where reads dominate, AVL's tighter balance usually beats a looser red-black tree, which performs fewer rotations but drifts taller.

The height balance factor

Height is measured in levels: an empty subtree has height 0 and a leaf has height 1, so a node's height is one plus the taller child's height. The balance factor of a node is the left height minus the right height. An AVL tree insists every balance factor stays within −1, 0 and +1, and anything beyond that means a rotation is owed.

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

def update_height(node):
    node.height = 1 + max(height(node.left), height(node.right))

def balance_factor(node):
    return height(node.left) - height(node.right)

A positive balance factor means the left side is taller and a negative one means the right. Once the factor passes +1 or −1, the shape is already determined: a left-heavy node with a left-heavy child is the LL case, a left-heavy node with a right-heavy child is the LR case, and the two right-heavy arrangements mirror them. Reading the factor as a compass makes the four repair paths easy to remember.

Left and right rotations, step by step

A right rotation lifts a node's left child into its place. Save the child as the new subtree root, move the child's right subtree across to become the old root's left child, then attach the old root as the new root's right child. Only a handful of pointers change, which is why rotation is O(1), and the height updates afterwards cost the same.

def rotate_right(y):
    x = y.left
    y.left = x.right
    x.right = y
    update_height(y)
    update_height(x)
    return x

def rotate_left(x):
    y = x.right
    x.right = y.left
    y.left = x
    update_height(x)
    update_height(y)
    return y

The left rotation is the mirror image: the right child rises, its left subtree swings across to the right, and the demoted node becomes its left child. Single rotations handle the zig-zig shapes. A left-left imbalance is repaired with one right rotation at the node, and a right-right imbalance with one left rotation. Key ordering survives because the pivot already sat between the smaller and larger keys.

Double rotations for zig-zag shapes

A zig-zag is trickier: the node is left-heavy, but its left child is right-heavy, so the path bends one way and then the other. Rotating once at the node would leave the imbalance sitting in the subtree. The repair takes two moves, a left rotation on the child followed by a right rotation on the node, and the middle key ends up on top.

def rebalance(node):
    update_height(node)
    bf = balance_factor(node)
    if bf > 1:
        if balance_factor(node.left) < 0:
            node.left = rotate_left(node.left)
        return rotate_right(node)
    if bf < -1:
        if balance_factor(node.right) > 0:
            node.right = rotate_right(node.right)
        return rotate_left(node)
    return node

The right-right and left-right cases mirror this: a right rotation on the right child, then a left rotation on the node. In code, the child's balance factor tells you which pre-rotation to apply, and the helper returns the new subtree root so the caller can splice it back into the parent. Two rotations still cost O(1), since the affected subtree is shallow and its size never changes.

Writing the class and inserting keys

Start with the node. Storing key, left, right and height in __slots__ keeps each node lean and blocks stray attributes, which matters when a tree holds hundreds of thousands of records.

class Node:
    __slots__ = ("key", "left", "right", "height")

    def __init__(self, key):
        self.key = key
        self.left = None
        self.right = None
        self.height = 1


class AVLTree:
    def __init__(self):
        self.root = None

    def insert(self, key):
        self.root = self._insert(self.root, key)

    def _insert(self, node, key):
        if node is None:
            return Node(key)
        if key < node.key:
            node.left = self._insert(node.left, key)
        elif key > node.key:
            node.right = self._insert(node.right, key)
        else:
            return node
        return rebalance(node)

Insertion recurses down the tree exactly as a plain binary search tree does, then unwinds. On the way back up, each node refreshes its height and asks the rebalancing helper whether it owes a rotation. Only the path to the new key is touched, so the operation stays logarithmic.

Decide what to do with duplicate keys early. The version here treats an equal key as a no-op, which suits sets and identifiers such as a customer number; if your application needs counts, keep a separate counter field on the node instead. For more algorithm background before going further, the hello ML community site collects open, community-written explainers on classic data structures and sorting methods.

Deleting keys and keeping the balance

Deletion has three cases. A leaf disappears, a node with one child hands that child up, and a node with two children takes the in-order successor, the smallest key in its right subtree, before deleting that key from the right subtree. The successor always fits the vacated spot, so the ordering survives.

def _delete(self, node, key):
    if node is None:
        return None
    if key < node.key:
        node.left = self._delete(node.left, key)
    elif key > node.key:
        node.right = self._delete(node.right, key)
    else:
        if node.left is None:
            return node.right
        if node.right is None:
            return node.left
        successor = self._minimum(node.right)
        node.key = successor.key
        node.right = self._delete(node.right, successor.key)
    return rebalance(node)

def _minimum(self, node):
    while node.left:
        node = node.left
    return node

The subtle part is rebalancing after the removal. Heights must be refreshed along the path back to the root, and a node may need a rotation even when the deletion happened far below it, because shortening one side can make the other side look too tall. Rebalance every ancestor, not just the parent of the removed key.

That care carries over to records with legal duties attached. A clinic indexing patient identifiers has to handle amendments under the Privacy Act 1988, and an index that quietly becomes lopsided slows every lookup in between. For a smaller everyday case, imagine a transport app indexing Opal card top-ups, where expired cards are deleted each morning and the survivors must still be searchable in logarithmic time.

Testing, traversal and real complexity

An in-order walk of an AVL tree visits keys in ascending order, which makes a natural correctness check. The iterative version below uses an explicit stack, so even a badly shaped tree cannot exhaust the recursion limit.

def in_order(self):
    keys, stack, node = [], [], self.root
    while stack or node:
        while node:
            stack.append(node)
            node = node.left
        node = stack.pop()
        keys.append(node.key)
        node = node.right
    return keys


def test_sorted_inserts_stay_balanced():
    tree = AVLTree()
    for value in range(64):
        tree.insert(value)
    assert tree.in_order() == list(range(64))
    assert tree.height() <= 7

For a comparison with another classic approach, the guide to comb sort shows how shrinking gap sequences turn an in-place array sort into something with a respectable average case. Building a tree is a different trade: inserting n keys one at a time costs O(n log n), while constructing a perfectly balanced tree from a sorted list by repeatedly taking the midpoint costs O(n) after the sort.

Space is O(n) for the nodes, with a constant handful of references each. In production, many Australian teams still reach for a battle-tested library or a plain dictionary when all they need is key-to-value lookup, and the Australian Consumer Law applies to whatever interface sits on top: a price-comparison site returning stale results through a broken index is misleading in a way regulators notice. Benchmark with realistic data, keep the balance invariants asserted in your tests, and the structure will hold its shape for years.