Height and skew
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
Insert 30 the plain BST way: more than 10, go right; more than 20, go right. It lands as a leaf. Climbing back up, each height grows by 1: 20 gets skew +1 and 10 gets +2. The rule breaks at 10.
Fix 10 with a left rotation: its right child 20 moves up into its place, and 10 drops to become 20's left child. Lines 3 and 4 re-point two links; line 5 recomputes both heights. Every skew is 0 again.
Look at the columns: no node moved sideways. Each column is a key's place in sorted order, and the in-order walk still reads 10, 20, 30. A rotation changes heights, never the order. It touches 3 links, whatever the tree's size: O(1).
Double rotation
Insert 25: more than 20, go right; less than 30, go left. Climbing back up, 30 gets skew −1 and 20 gets +1. Every skew is still between −1 and +1, so no rotation is needed.
Insert 27: right of 20, left of 30, right of 25. Now 25 has skew +1, 30 has −2 and 20 has +2. Fix the lowest broken node, 30. It leans left, but its child 25 leans right: a zig-zag.
A single rotation at 30 would only flip the lean. So first rotate left at the child, 25: 27 moves up and 25 drops to its left. Now 30, 27 and 25 lean the same way, a straight line like the one at 10.
Then rotate right at 30, the mirror image of rotate_left. 27 moves up into 30's place, with 25 and 30 as its children. That subtree is back to its old height, 1, so 20 returns to skew +1. Balanced again.
Why it pays
With every skew between −1 and +1, a tree of height h has at least 2^(h/2) nodes, so h ≤ 2·log₂ n. Search, insert and delete walk one path: O(log n). Each insert needs at most one single or double rotation.
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.