AlgoFrames

AVL trees and rotations

An AVL tree keeps the heights of every node’s subtrees within one. Single and double rotations restore balance after an insert.

Before you start: Why balance matters.

The idea

Insert 1, 2, 3 into a plain BST and a chain starts. An AVL tree spots the lopsided node 1 and lifts 2 on top at once.

A plain BST never fixes its shape, so sorted input makes search linear. An AVL tree checks the shape after every insert.

Intuition

A node's balance factor is its left height minus its right height. An AVL tree keeps every balance factor at -1, 0 or +1.

With that rule the height stays below about 1.44 log2 n, so search, insert and delete all stay O(log n).

A left rotation lifts 20 and lowers 10. The middle subtree 15 moves from 20 to 10, and the key order stays the same.

15 is bigger than 10 and smaller than 20, so it can hang on either side. Only three links change, so a rotation costs O(1).

Complexity

Sorted keys make a plain BST as tall as n. An AVL tree stays O(log n) tall, so insert costs O(log n) with at most two rotations.

Insert walks one root-to-leaf path and back up, updating heights. Each rotation changes three links in O(1). The tree uses O(n) space.

Pitfalls

One rotation cannot fix a zig-zag. Rotating right at 3 just mirrors it, so rotate the child 1 left first.

The middle key 2 must end up on top. A single rotation lifts 1 instead, so the imbalance flips to the other side.

Variations

Red-black trees allow a looser balance and recolour nodes, so they rotate less often. Treaps and splay trees balance in other ways.

AVL trees are more tightly balanced, so lookups are a little faster. Red-black trees do fewer rotations on insert and delete.

Code

Pseudocode

insert(node, 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)
  update height(node)
  b ← height(node.left) − height(node.right)
  if b > 1 and key > node.left.key: node.left ← rotateLeft(node.left)
  if b > 1: return rotateRight(node)
  if b < −1 and key < node.right.key: node.right ← rotateRight(node.right)
  if b < −1: return rotateLeft(node)
  return node

Python

def insert(node, key):
    if node is None:
        return Node(key)
    if key < node.key:
        node.left = insert(node.left, key)
    else:
        node.right = insert(node.right, key)
    update(node)
    b = height(node.left) - height(node.right)
    if b > 1 and key > node.left.key:
        node.left = rotate_left(node.left)
    if b > 1:
        return rotate_right(node)
    if b < -1 and key < node.right.key:
        node.right = rotate_right(node.right)
    if b < -1:
        return rotate_left(node)
    return node

JavaScript

function insert(node, 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);
  update(node);
  const b = height(node.left) - height(node.right);
  if (b > 1 && key > node.left.key) node.left = rotateLeft(node.left);
  if (b > 1) return rotateRight(node);
  if (b < -1 && key < node.right.key) node.right = rotateRight(node.right);
  if (b < -1) return rotateLeft(node);
  return node;
}

Java

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);
  update(node);
  int b = height(node.left) - height(node.right);
  if (b > 1 && key > node.left.key) node.left = rotateLeft(node.left);
  if (b > 1) return rotateRight(node);
  if (b < -1 && key < node.right.key) node.right = rotateRight(node.right);
  if (b < -1) return rotateLeft(node);
  return node;
}

Cost at a glance

AccessO(log n)
SearchO(log n)
InsertO(log n)
DeleteO(log n)
SpaceO(n)

Practice problems (6)

Identify the rotation Warm-up

The keys 20, 10, 15 were inserted into an empty AVL tree. Before any repair the tree looks like the picture: 20 has balance +2. Which repair restores the AVL property?

Spot the unbalanced node Warm-up

The keys 1, 2, 3, 4, 5 are inserted in this order into an empty AVL tree. Each node shows its balance factor: left height minus right height.

Answer each question before the step plays.

Insert and rebalance Standard

The keys 20, 10, 30, 5, 15, 12 are inserted in this order into an empty AVL tree. The array next to the tree lists the keys in level order: the root, then each level from left to right.

Answer each question before the step plays.

Implement rotate-left Standard

Rotate the BST with root x to the left and return the new root. The right child y of x moves up, x becomes the left child of y, and the old left subtree of y becomes the right subtree of x.

If x is null or has no right child, return x unchanged.

Implement rotate-right Standard

Rotate the BST with root x to the right and return the new root. The left child y of x moves up, x becomes the right child of y, and the old right subtree of y becomes the left subtree of x.

If x is null or has no left child, return x unchanged.

Implement AVL insert Challenge

Insert the distinct integers keys, in the given order, into an empty AVL tree and return its root.

After each insert, walk back up the path. At the first node whose subtree heights differ by more than 1, apply the standard fix: one rotation for the left-left and right-right cases, two rotations for the left-right and right-left cases. You may keep the heights in a map, since TreeNode has only val, left and right.

Related topics

Next on the path: Red-black trees