Skip to lesson content
navan✳THE BUILD LABPYTHON 3
0/101 complete
BUILD LAB / PYTHON/ Think in algorithms
EXPERIMENT 76 / 101

Keep the branches in balance.

Understand height balance and implement a rebalancing insertion.

ADVANCED LAB
BY NAVAN SAMI◷ 16 MIN READPYTHON 3

01 The idea

An AVL tree maintains a height difference of at most one between each node’s subtrees. Insertion first follows ordinary BST ordering, then updates heights and performs rotations when a balance factor leaves the allowed range. Single and double rotations restore the invariant while preserving in-order key order. This makes search, insertion, and deletion logarithmic in a correctly implemented AVL tree; the exercise implements insertion only.

02 The experiment

Read it once. Predict what will happen. Then copy it into a .py file and run it in your local Python setup.

avl_trees.py
class Node:
    def __init__(self, value):
        self.value, self.left, self.right, self.height = value, None, None, 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 rotate_right(root):
    child = root.left
    root.left, child.right = child.right, root
    update(root); update(child)
    return child
def rotate_left(root):
    child = root.right
    root.right, child.left = child.left, root
    update(root); update(child)
    return child

def insert(root, value):
    if root is None: return Node(value)
    if value < root.value: root.left = insert(root.left, value)
    elif value > root.value: root.right = insert(root.right, value)
    else: return root
    update(root)
    balance = height(root.left) - height(root.right)
    if balance > 1:
        if value > root.left.value: root.left = rotate_left(root.left)
        return rotate_right(root)
    if balance < -1:
        if value < root.right.value: root.right = rotate_right(root.right)
        return rotate_left(root)
    return root
root = None
for value in [30, 20, 10]: root = insert(root, value)
print(root.value, root.height)
↳ EXPECTED OUTPUT
20 2

03 Under the hood

  1. 1

    A leaf height is one and an absent child height is zero. Update heights after changing links, and update the old root before the new root during rotation.

  2. 2

    The left-right and right-left cases require rotating the child first. A single outer rotation then restores balance.

  3. 3

    The short fixture triggers a left-left imbalance. Real tests should include all four rotation cases and recursively verify sorted order, stored heights, and balance factors after every insertion.

04 Your turn, builder

A SMALL MISSION

Test the four three-key rotation cases and verify that each final root is 20. Use the lesson’s insertion functions, then add a recursive invariant checker.

Reveal one possible solution +
one_possible_solution.py
class Node:
    def __init__(self, value):
        self.value, self.left, self.right, self.height = value, None, None, 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 rotate_right(root):
    child = root.left
    root.left, child.right = child.right, root
    update(root); update(child)
    return child
def rotate_left(root):
    child = root.right
    root.right, child.left = child.left, root
    update(root); update(child)
    return child

def insert(root, value):
    if root is None: return Node(value)
    if value < root.value: root.left = insert(root.left, value)
    elif value > root.value: root.right = insert(root.right, value)
    else: return root
    update(root)
    balance = height(root.left) - height(root.right)
    if balance > 1:
        if value > root.left.value: root.left = rotate_left(root.left)
        return rotate_right(root)
    if balance < -1:
        if value < root.right.value: root.right = rotate_right(root.right)
        return rotate_left(root)
    return root
def check(node, low=float('-inf'), high=float('inf')):
    if node is None: return 0
    assert low < node.value < high
    left = check(node.left, low, node.value)
    right = check(node.right, node.value, high)
    assert abs(left - right) <= 1
    assert node.height == 1 + max(left, right)
    return node.height
for values in [[30,20,10], [10,20,30], [30,10,20], [10,30,20]]:
    root = None
    for value in values:
        root = insert(root, value)
        check(root)
    assert root.value == 20
print("Four rotation cases and invariants passed")

05 Check your signal

QUICK SIGNAL CHECK

What invariant does an AVL tree maintain?

THAT’S ANOTHER IDEA IN YOUR TOOLKIT.

Experiment. Logged.

When you can explain the idea and make the example your own, mark it complete. Your log stays in this browser.

Keep exploring

Go deeper with the official Python guide ↗.

Built with curiosity. By Navan Sami. ↗Python 3 · Think. Try. Build.