ENع
←AVL trees
Lesson 16 · Search trees

AVL trees and rotations

14 min9 steps5 questionsIntermediate
About this lesson

A binary search tree is only fast while it stays bushy. The Software lesson "Trees" shows search and insert, and how sorted inserts turn a tree into a line. An AVL tree stops that from happening. Every node stores its height and keeps its skew (right height minus left height) at −1, 0 or +1. When an insert breaks that rule, one or two rotations fix it in constant time and never change the sorted order. Insert 10, 20, 30, 25 and 27 and watch both kinds of fix. The Databases lesson "B-trees" covers a different balanced tree, built with wide nodes for disk.

You'll learn to

Tick what you feel confident about. These self-checks do not affect your lesson score.

Fig 16 · Interactive
01 / 09

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.

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
Loading figure…
or ← →
Read the lesson step by step
  1. 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.

    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
  2. Insert 30, climb back up

    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.

    compare: 30 > 10 → right, 30 > 20 → right
    
    key  height  skew
     10       2    +2
     20       1    +1
     30       0     0
    
    skew(10) = +2: right-heavy, a straight line 10 → 20 → 30
  3. A left rotation

    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.

    rotate_left(10):
      y = x.right       y is 20
      x.right = y.left  10.right = None
      y.left = x        20.left = 10
      fix(x); fix(y)    heights 0 and 1
      return y          20 is the new root
    
    key  height  skew
     10       0     0
     20       1     0
     30       0     0
  4. The order never changes

    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).

    in-order before: 10 20 30
    in-order after:  10 20 30
    
    links changed: 10.right, 20.left and the root
    the same 3 for any tree size: O(1) time
  5. Insert 25: still fine

    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.

    compare: 25 > 20 → right, 25 < 30 → left
    
    key  height  skew
     10       0     0
     20       2    +1
     25       0     0
     30       1    −1
    
    all skews in −1..+1: nothing to fix
  6. Insert 27: a zig-zag

    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.

    compare: 27 > 20 → right, 27 < 30 → left, 27 > 25 → right
    
    key  height  skew
     10       0     0
     20       3    +2
     25       1    +1
     27       0     0
     30       2    −2
    
    lowest node out of range: 30 (−2)
    its left child 25 leans the other way (+1): zig-zag
  7. First, rotate the child

    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.

    rebalance(30): skew −2, and skew(30.left) = +1 > 0
      n.left = rotate_left(n.left)   rotate_left(25)
    
    key  height  skew
     10       0     0
     20       3    +2
     25       0     0
     27       1    −1
     30       2    −2
    
    30 → 27 → 25 is now a straight line to the left
  8. Then rotate the node

    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.

      return rotate_right(n)         rotate_right(30)
    
    key  height  skew
     10       0     0
     20       2    +1
     25       0     0
     27       1     0
     30       0     0
    
    subtree height: 1 before 27 came, 1 again now
    so nothing above it changes: one fix per insert
  9. 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.

    fewest nodes F(h) in an AVL tree of height h:
      F(0) = 1, F(1) = 2, F(h) = 1 + F(h−1) + F(h−2)
      F(h) ≥ 2·F(h−2), so F(h) ≥ 2^(h/2)
      n ≥ 2^(h/2)  ⇒  h ≤ 2·log₂ n
    
    the whole program (Python 3, runs as-is):
    
    class Node:
        def __init__(self, key):
            self.key = key
            self.left = self.right = None
            self.height = 0          # a leaf has height 0
    
    def h(n):
        return n.height if n else -1  # an empty subtree is -1
    
    def fix(n):
        n.height = 1 + max(h(n.left), h(n.right))
    
    def skew(n):
        return h(n.right) - h(n.left)
    
    def rotate_left(x):
        y = x.right
        x.right = y.left
        y.left = x
        fix(x); fix(y)
        return y
    
    def rotate_right(x):
        y = x.left
        x.left = y.right
        y.right = x
        fix(x); fix(y)
        return y
    
    def rebalance(n):
        fix(n)
        if skew(n) == 2:                 # right-heavy
            if skew(n.right) < 0:        # zig-zag: turn it into a line
                n.right = rotate_right(n.right)
            return rotate_left(n)
        if skew(n) == -2:                # left-heavy
            if skew(n.left) > 0:         # zig-zag
                n.left = rotate_left(n.left)
            return rotate_right(n)
        return n
    
    def insert(n, key):
        if n is None:
            return Node(key)
        if key < n.key:
            n.left = insert(n.left, key)
        else:
            n.right = insert(n.right, key)
        return rebalance(n)              # fix heights on the way back up
    
    def preorder(n):
        return [n.key] + preorder(n.left) + preorder(n.right) if n else []
    
    root = None
    for key in [10, 20, 30, 25, 27]:
        root = insert(root, key)
    print(*preorder(root))
    
    output: 20 10 27 25 30

Quiz Unlocks after the last step.