10202527301def rotate_left(x):2 y = x.right3 x.right = y.left4 y.left = x5 fix(x); fix(y)6 return y
Node blocks: key on top, skew below; a yellow pill marks a skew of ±2Columns: each key's place in sorted order, matched by the row in frontThe chip: a key on its way down to be insertedEach node shows its key and its skew, the height of its right subtree minus its left; an AVL tree keeps every skew at −1, 0 or +1. Inserting 30 breaks the rule at 10 and one left rotation fixes it; inserting 27 makes a zig-zag under 30, fixed by two rotations. Nodes only move up and down in their columns: a rotation never changes the sorted order.

Height and skew

  1. An AVL tree is a BST that stays balanced. Each node stores its height, the longest path down to a leaf (a leaf is 0, a missing child −1). Skew = right height − left height. Rule: every skew is −1, 0 or +1.

Single rotation

Double rotation

Why it pays

What happens

;; step 1/9 · heights
key  height  skew
 10       1    +1
 20       0     0

10 has no left child (−1) and a right child of height 0:
skew(10) = 0 − (−1) = +1, inside the rule

This lesson follows MIT 6.006 and defines skew as right height minus left height. Sedgewick and Wayne's AVLTreeST uses the opposite sign (left minus right) and calls it the balance factor. The rule, a value of −1, 0 or +1 at every node, is the same. In the figure each key has its own column in sorted order, with gaps kept for keys that arrive later. That makes it visible that a rotation only moves nodes up and down, never left or right.