TExcelTAD

AVL Trees

An AVL tree (named after its inventors Adelson-Velsky and Landis, 1962) is a binary search tree that keeps itself balanced. After every insertion or deletion it checks the heights of the subtrees and, if they have drifted apart, fixes the shape with small local operations called rotations. This guarantees a height of about 1.44 log₂ n at most, so search, insert and delete are always O(log n), even for sorted input that would turn a plain BST into a chain.

The balance factor

Every node stores its height. Its balance factor is:

text
balance(node) = height(node.left) - height(node.right)

The AVL rule: every node's balance factor must be -1, 0 or +1. An empty subtree has height -1 (some books use 0; only the differences matter).

python · try it yourself
class Node:
    def __init__(self, value, left=None, right=None):
        self.value, self.left, self.right = value, left, right

def height(n):
    return -1 if n is None else 1 + max(height(n.left), height(n.right))

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

ok = Node(20, Node(10, Node(5)), Node(30))
bad = Node(20, Node(10, Node(5, Node(2))), Node(30))
for name, root in [("ok", ok), ("bad", bad)]:
    print(name, "root balance:", balance(root), "left child balance:", balance(root.left))
ok root balance: 1 left child balance: 1
bad root balance: 2 left child balance: 2

In bad, the root's left side is two levels taller than its right side: balance factor +2, so the AVL rule is broken.

Rotations

A right rotation at node y lifts its left child x up and moves y down to the right. The subtree B between them changes parent. In-order order is preserved, so the result is still a valid BST:

text
        y                x
       / \              / \
      x   C    ==>     A   y
     / \                  / \
    A   B                B   C

A left rotation is the mirror image. There are four imbalance cases after an insertion, named by the path from the unbalanced node to the new value:

Case Shape Fix
Left-Left balance > 1, new value went left of the left child right rotation
Right-Right balance < -1, new value went right of the right child left rotation
Left-Right balance > 1, new value went right of the left child left-rotate the child, then right-rotate
Right-Left balance < -1, new value went left of the right child right-rotate the child, then left-rotate

Implementation

python · try it yourself
class Node:
    def __init__(self, value):
        self.value = value
        self.left = self.right = None
        self.height = 0

def h(n):
    return n.height if n else -1

def update(n):
    n.height = 1 + max(h(n.left), h(n.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 insert(node, value):
    if node is None:
        return Node(value)
    if value < node.value:
        node.left = insert(node.left, value)
    else:
        node.right = insert(node.right, value)
    update(node)
    bal = h(node.left) - h(node.right)
    if bal > 1 and value < node.left.value:
        print(f"  Left-Left at {node.value}: rotate right")
        return rotate_right(node)
    if bal < -1 and value > node.right.value:
        print(f"  Right-Right at {node.value}: rotate left")
        return rotate_left(node)
    if bal > 1:
        print(f"  Left-Right at {node.value}: rotate {node.left.value} left, then {node.value} right")
        node.left = rotate_left(node.left)
        return rotate_right(node)
    if bal < -1:
        print(f"  Right-Left at {node.value}: rotate {node.right.value} right, then {node.value} left")
        node.right = rotate_right(node.right)
        return rotate_left(node)
    return node

def preorder(n):
    return [n.value] + preorder(n.left) + preorder(n.right) if n else []

root = None
for v in [30, 20, 10, 40, 50, 25, 22, 23]:
    print(f"insert {v}")
    root = insert(root, v)
print("pre-order:", preorder(root), "height:", root.height)
insert 30
insert 20
insert 10
  Left-Left at 30: rotate right
insert 40
insert 50
  Right-Right at 30: rotate left
insert 25
  Right-Left at 20: rotate 40 right, then 20 left
insert 22
insert 23
  Left-Right at 25: rotate 22 left, then 25 right
pre-order: [30, 20, 10, 23, 22, 25, 40, 50] height: 3

Inserting 30, 20, 10 creates a Left-Left case at 30. Then 40 and 50 create a Right-Right case at 30 (by now a child of 20). Inserting 25 makes the root 20 right-heavy with a Right-Left shape, so 30 becomes the new root. 22 fits without any rotation, and 23 makes 25 left-heavy with a Left-Right shape. After every insertion the tree is balanced again. The final tree is:

text
            30
          /    \
        20      40
       /  \       \
     10    23      50
          /  \
        22    25

Sorted input, no problem

The plain BST from the previous lesson degenerated into a chain of height 100 when fed sorted values. The AVL tree stays shallow:

python · try it yourself
class Node:
    def __init__(self, value):
        self.value, self.left, self.right, self.height = value, None, None, 0

def h(n): return n.height if n else -1
def update(n): n.height = 1 + max(h(n.left), h(n.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

rotations = 0
def insert(node, value):
    global rotations
    if node is None:
        return Node(value)
    if value < node.value: node.left = insert(node.left, value)
    else:                  node.right = insert(node.right, value)
    update(node)
    bal = h(node.left) - h(node.right)
    if bal > 1:
        if value > node.left.value:
            node.left = rotate_left(node.left); rotations += 1
        rotations += 1
        return rotate_right(node)
    if bal < -1:
        if value < node.right.value:
            node.right = rotate_right(node.right); rotations += 1
        rotations += 1
        return rotate_left(node)
    return node

for n in [7, 101, 1000]:
    root, rotations = None, 0
    for v in range(n):
        root = insert(root, v)
    print(f"{n:>5} sorted inserts: height {root.height}, {rotations} rotations")
    7 sorted inserts: height 2, 4 rotations
  101 sorted inserts: height 6, 94 rotations
 1000 sorted inserts: height 9, 990 rotations

Inserting 1000 sorted values yields a height of 9, the minimum possible (⌊log₂ 1000⌋ = 9). Each rotation only touches a few pointers, so balancing adds just O(1) work per level on the way back up.

AVL vs other balanced trees

Tree Balance rule Notes
AVL heights differ by ≤ 1 strictly balanced: fastest lookups
Red-black colour rules; height ≤ 2 log₂(n+1) fewer rotations on updates; used by Java TreeMap, C++ std::map
B-tree many keys per node databases and file systems (few disk reads)

Deletion in an AVL tree works like BST deletion followed by the same rebalancing on the way back up; it may need rotations at several levels.

Test yourself

Which balance factors are allowed in an AVL tree?

  1. Only 0
  2. -1, 0 and +1
  3. -2 to +2
  4. Any, as long as the root is balanced

Inserting 10, 20, 30 (in that order) into an empty AVL tree triggers which case?

  1. Left-Left
  2. Right-Right
  3. Left-Right
  4. Right-Left

Does a rotation change the in-order sequence of a BST?

  1. Yes, it reverses it
  2. No, the BST ordering is preserved
  3. Only for left rotations
  4. Only at the root