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.

Implementing a red-black tree insertion with recursive fixup in Python

A red-black tree is a binary search tree whose shape is constrained to keep operation costs predictable. Every node carries a red or black colour, the root is black, red nodes have black children, and each route to a descendant leaf contains the same number of black nodes. In Python, None can represent the black sentinel leaves, avoiding a separate terminal object for every absent child.

Insertion has two phases in this design: place the key as in an ordinary binary search tree, then repair any broken invariant. The new node starts red because it cannot change the black-height of existing paths. A recursive fixup then handles a red parent, the uncle, and the required recolouring or rotation. The identifier colour follows Australian spelling, while the algorithm itself remains the standard textbook formulation.

The trade-off matters in Australian software settings. Sydney fintech services often need predictable membership checks, Melbourne marketplace teams may keep catalogues ordered by identifier, and Canberra public-sector developers benefit from code that is easy to audit. A dependable tree can support those workloads without depending on a third-party package.

The invariants that insertion can break

The tree relies on five related properties: each node has one colour; the root is black; all None children act as black leaves; a red node cannot have a red child; and both subtrees of every node have equal black-height. Search order still comes from the binary search tree rule, so every key in a left subtree remains smaller than its node's key.

A normal insertion descends until it reaches None, creates a red node there, and links it to its parent. This preserves key order, but a red parent can give the new red node a red child. That single violation can also disturb black-height when later rotations are required.

Repair is therefore not an arbitrary tidy-up. The parent, child, grandparent, and uncle determine which of two strategies is safe: recolour the local group and move the concern upward, or rotate to turn the straight shape into a balanced one. The explicit discipline is similar to the assumptions behind broader machine-learning foundations, although a red-black tree is fully deterministic.

Building a recursive insertion path

The node stores a key, optional value, child links, parent link, and colour. Duplicate keys are rejected instead of silently replacing a payload; an update policy would need to preserve the existing node’s colour.

RED = "red"
BLACK = "black"


class RBNode:
    __slots__ = ("key", "value", "left", "right", "parent", "colour")

    def __init__(self, key, value=None):
        self.key = key
        self.value = value
        self.left = None
        self.right = None
        self.parent = None
        self.colour = RED


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

    def insert(self, key, value=None):
        new_node = RBNode(key, value)
        self.root = self._bst_insert(self.root, new_node)
        self._fix_insert(new_node)
        self.root.colour = BLACK
        return new_node

    def _bst_insert(self, node, new_node):
        if node is None:
            return new_node

        if new_node.key == node.key:
            raise ValueError(f"Key already exists: {new_node.key}")

        if new_node.key < node.key:
            node.left = self._bst_insert(node.left, new_node)
            node.left.parent = node
        else:
            node.right = self._bst_insert(node.right, new_node)
            node.right.parent = node

        return node

The _bst_insert method is recursive because its next position depends on the current key. It also maintains parent links, allowing the repair phase to move upwards without searching for ancestors again.

Keeping search and repair separate is deliberate. It avoids returning a replacement subtree root from every recursive level while a higher rotation may already have changed an ancestor’s child pointer. The tree is briefly invalid after placement, then _fix_insert repairs it from the inserted node.

Repairing the red-red violation

Repair begins only when the inserted node and its parent are red. The grandparent must be black before repair begins, and the uncle is either red or black. These two facts determine the branch taken by _fix_insert.

    def _fix_insert(self, node):
        parent = node.parent

        if node.colour != RED or parent is None or parent.colour != RED:
            return

        grandparent = parent.parent
        if grandparent is None:
            raise RuntimeError("A red parent must have a grandparent")

        if parent is grandparent.left:
            uncle = grandparent.right

            if uncle is not None and uncle.colour == RED:
                parent.colour = BLACK
                uncle.colour = BLACK
                grandparent.colour = RED
                return self._fix_insert(grandparent)

            if node is parent.right:
                self._rotate_left(parent)
                node = parent
                parent = node.parent
                grandparent = parent.parent

            parent.colour = BLACK
            grandparent.colour = RED
            self._rotate_right(grandparent)

        else:
            uncle = grandparent.left

            if uncle is not None and uncle.colour == RED:
                parent.colour = BLACK
                uncle.colour = BLACK
                grandparent.colour = RED
                return self._fix_insert(grandparent)

            if node is parent.left:
                self._rotate_right(parent)
                node = parent
                parent = node.parent
                grandparent = parent.parent

            parent.colour = BLACK
            grandparent.colour = RED
            self._rotate_left(grandparent)

In the red-uncle branch, the parent and uncle become black while the grandparent becomes red. That removes the immediate red-red pair but may expose the same condition one level higher, so the method calls itself with the grandparent. The recursion stops when its parent is black or absent.

In the black-uncle branch, a straight line becomes a suitable shape through one rotation, while a bent line first needs a rotation to straighten it and then another to finish. Recolouring accompanies those rotations. The final root recolour in insert handles the special case where a recoloured grandparent was the root.

Rotations that preserve every reference

Rotations are local pointer changes that retain binary search order. A left rotation promotes the right child, while a right rotation promotes the left child.

    def _rotate_left(self, x):
        y = x.right
        if y is None:
            raise ValueError("Cannot rotate without a right child")

        x.right = y.left
        if y.left is not None:
            y.left.parent = x

        y.parent = x.parent
        if x.parent is None:
            self.root = y
        elif x is x.parent.left:
            x.parent.left = y
        else:
            x.parent.right = y

        y.left = x
        x.parent = y
        return y

    def _rotate_right(self, x):
        y = x.left
        if y is None:
            raise ValueError("Cannot rotate without a left child")

        x.left = y.right
        if y.right is not None:
            y.right.parent = x

        y.parent = x.parent
        if x.parent is None:
            self.root = y
        elif x is x.parent.left:
            x.parent.left = y
        else:
            x.parent.right = y

        y.right = x
        x.parent = y
        return y

Each helper first transfers the inner subtree, then replaces the old child with the promoted node, and finally makes the old parent a child of the promoted node. Updating both child and parent links is essential because fixup navigates upward through them.

The mirrored fixup branches rely on identical rotation mechanics. Ignoring the returned rotation result is safe because the helpers update self.root and the parent’s child pointer immediately; _fix_insert only needs to know that the shape has changed.

Verification routines and practical checks

A compact validator should check these conditions after every insertion:

A repeatable test set should cover these situations:

These checks separate algorithmic errors from Python implementation errors. A wrong parent pointer may still leave sorted output looking correct, while broken black-height can preserve ordering but cause later insertions to rotate incorrectly. Running both structural and ordering checks provides stronger evidence that the tree remains usable.

Performance and neighbouring data structures

A balanced tree of n keys has height O(log n). The search for the insertion point is O(log n), the recolouring recursion is O(log n) in the worst case, and repair performs at most two rotations. The implementation uses O(log n) recursion space and O(n) total node storage. Because None leaves are implicit, each key requires only one Python object.

A red-black tree is a strong choice when keys need ordered traversal, predecessor and successor access, or frequent updates without shifting an entire list. For range-only aggregation, a range-query segment tree offers a different balance. When ordering is maintained by a database instead, its indexing strategy changes the cost model.

That distinction is important for Australian APIs backed by relational stores: a fast in-memory tree does not remove database latency. index-aware SQL guidance covers how indexes and execution plans affect lookups, while a tree remains useful when application logic requires ordered access beyond a single indexed query. These structures let engineers match the data structure to the workload rather than treating one index as a universal answer.