Data Structures · Trees

AVL trees

An AVL tree is a binary search tree that keeps itself balanced. After every insert it checks the heights on the way back up, and if one side of a node has grown two levels taller than the other, it fixes that with one or two rotations. The height stays O(log n), so search and insert stay fast no matter what order the keys arrive in.

The balance rule

Each node stores its height: a leaf has height 1, and an empty subtree has height 0. The balance factor of a node is

balance = height(left subtree) − height(right subtree)

A BST is an AVL tree when every node has a balance factor of −1, 0 or +1. In other words, at every node the two subtrees differ in height by at most one. Positive means the node leans left; negative means it leans right.

An AVL tree. The small number by each node is its balance factor. Every one is −1, 0 or +1.
Not an AVL tree. It is still a valid BST, but 8 and 12 each have a balance factor of +2: their left subtrees are two levels taller than their right ones.
Stop and think
In the AVL tree on the left, check the balance factor of 8 yourself.

8's left subtree is 5 with child 4, so it has height 2. Its right subtree is the single node 11, height 1. The balance factor is 2 − 1 = +1, which is allowed.

Is every complete binary tree an AVL tree? Is every AVL tree complete?

Every complete tree is AVL: its levels are full except the last, so no two sibling subtrees differ in height by more than one. The reverse is false. The AVL tree on the left is not complete: 18 has no right child, yet the level below already holds 4. AVL allows gaps anywhere, as long as heights stay within one.

Why bother?

Search, insert, delete, min and max in a BST all follow one path from the root, so they cost O(h), where h is the height. If keys arrive in sorted order, a plain BST turns into a chain and h = n: no better than a linked list.

An AVL tree repairs itself after each insert so that h stays O(log n). In fact the height is never more than about 1.44 log₂ n, so a million keys never need more than about 28 levels, compared with a million levels for a sorted chain.

Insert the keys 1, 2, 3, …, n in orderPlain BST heightAVL tree height
n = 773
n = 15154
n = 1,0001,00010
n = 1,000,0001,000,00020

Rotations

A rotation changes the shape of a small part of the tree without breaking the BST order. It moves one node up a level and its parent down a level.

In a right rotation at y, y's left child x moves up and y becomes x's right child. x's old right subtree T2 has to move somewhere: it becomes y's new left subtree. A left rotation is the mirror image, and undoes it.

The order is the same in both pictures: keys(T1) < x < keys(T2) < y < keys(T3). T2 is between x and y either way, which is why it can switch parents. Only a few pointers change, so a rotation costs O(1) no matter how big the subtrees are.

right rotate (y) →
← left rotate (x)
Right and left rotation. T1, T2 and T3 are whole subtrees, possibly empty. Only T2 changes parent.
Node* rightRotate(Node* y) {
    Node* x = y->left;
    Node* T2 = x->right;

    x->right = y;      // y moves down to the right of x
    y->left = T2;      // T2 changes parent

    // y is now below x, so update y first
    y->height = std::max(getHeight(y->left), getHeight(y->right)) + 1;
    x->height = std::max(getHeight(x->left), getHeight(x->right)) + 1;
    return x;          // new root of this subtree
}

Rotation playground

Click a node to select it, then rotate there. Watch the inorder sequence: it never changes. Can you turn this chain into a tree of height 3 using rotations alone?

Stop and think
When you rotate at a node, which pointers change?

Three: x's right pointer (now y), y's left pointer (now T2), and whatever pointed to y before (its parent's pointer, or the root), which now points to x. In the C++ the third one happens when the caller stores the returned pointer.

Why must y's height be updated before x's?

After the rotation y is x's child, and x's height is computed from its children's heights. If x were updated first it would use y's old, wrong height.

How few rotations does the chain 1 to 7 need to reach height 3?

Four will do it. Rotate left at 1, then at 3, then at 5: each pulls the next node up, making 2, 4 and 6 the spine with 1, 3, 5, 7 hanging off. Then rotate left at 2 to make 4 the root, giving 4 with children 2 and 6, and leaves 1, 3, 5, 7.

Insertion

Insert the new key w exactly as in a plain BST, as a new leaf. Only the nodes on the path from the root to w can have changed height, so only they can become unbalanced. Then:

  1. Walk back up from w, updating each node's height.
  2. Let z be the first node on the way up whose balance factor is +2 or −2.
  3. Let y be z's child on the path to w, and x be y's child on that path.
  4. Rebalance the subtree rooted at z with one or two rotations, depending on how z, y and x are arranged.

The recursive insert gets step 1 for free: as each recursive call returns, it is back at the next ancestor, so it can update that node's height and check its balance without any parent pointers.

z: first unbalanced nodey: its child toward wx: its grandchild toward w
right rotate (z) →
1. Left Left. y is z's left child and x is y's left child. One right rotation at z lifts y to the top.
left rotate (y) →
right rotate (z) →
2. Left Right. y is z's left child but x is y's right child: a zig-zag. A left rotation at y straightens it into the Left Left shape, then a right rotation at z lifts x to the top.
left rotate (z) →
3. Right Right. The mirror of Left Left: one left rotation at z.
right rotate (y) →
left rotate (z) →
4. Right Left. The mirror of Left Right: a right rotation at y, then a left rotation at z.

In all four cases the middle key of z, y and x ends up on top, with the other two as its children and T1 to T4 in order underneath. The rebalanced subtree has the same height it had before the insert, so no ancestor above z sees any change. One insert needs at most one rebalance, either a single or a double rotation.

Stop and think
Insert 30, 20, 10 into an empty AVL tree by hand. Which node is z, and which case is it?

After 10 goes in as 20's left child, 30 has a left subtree of height 2 and an empty right subtree: balance +2, so z = 30, y = 20, x = 10. Left then left: the Left Left case. A right rotation at 30 gives 20 with children 10 and 30. Check it with the "Left Left" preset below.

The code never stores x. How does it tell Left Left from Left Right?

It compares the new key with y's key. If z leans left (balance > 1) and the key is smaller than node->left->key, the key went left at y too: Left Left. If it is larger, it went right at y: Left Right.

Why can't a single right rotation fix the Left Right case?

Try it: with z = 30, y = 10, x = 20, a right rotation at 30 makes 10 the root with 30 as its right child and 20 as 30's left child. That leans right by 2 instead of left by 2. The first rotation at y is what turns the zig-zag into a straight line that one rotation can fix.

Try it

Each insert steps through the C++ on the right: down the tree as a normal BST insert, then back up, updating heights and checking balance factors, with any rotations animated.

Presets
Show

The tree

zyxheight just updated

Badges show each node's stored height field, or the balance factor computed from its children's stored heights. Nodes above the insert keep their old heights until the recursion returns to them.

Output

Call stack

    What is happening

    AVLTree.cpp

      Stop and think
      Before running the class main() (10 20 30 40 50 25), predict which inserts cause rotations, and which case each one is.

      30 causes a Right Right at 10. 50 causes a Right Right at 30. 25 causes a Right Left at 20 (z = 20, y = 40, x = 30). 20, 40 and 10 cause none. The final tree has 30 at the root, preorder 30 20 10 25 40 50.

      Insert 1 through 7 in order. What shape do you get?

      A perfect tree: 4 at the root, 2 and 6 below it, and 1, 3, 5, 7 as leaves. A plain BST would have made a chain of height 7. Try "Sorted 1–15" to see the same thing at height 4.

      After an insert, if a node's height does not change, can any node above it become unbalanced?

      No. Its ancestors' heights are computed from its height, so nothing above it changes either. The class code keeps checking all the way up anyway; that is simpler and still O(log n), but a faster version could stop early.

      Cost

      OperationAverageWorst
      TraversalO(n)O(n)
      SearchO(log n)O(log n)
      InsertO(log n)O(log n)
      DeleteO(log n)O(log n)

      Insert walks down one path (O(log n)), then back up the same path doing O(1) work per node: a height update, a balance check, and at most one single or double rotation in total. Deletion uses the same height updates and the same four rotations, but removing a node can shorten a subtree, so it may need to rebalance at several ancestors on the way up. That is still O(log n).

      Stop and think
      What is the fewest nodes an AVL tree of height 4 can have?

      7. The sparsest AVL tree of height h has one subtree of height h − 1 and the other of height h − 2, each as sparse as possible. So N(h) = N(h − 1) + N(h − 2) + 1, with N(1) = 1 and N(2) = 2. That gives N(3) = 4 and N(4) = 7. These counts grow like Fibonacci numbers, which is where the 1.44 log₂ n height bound comes from.

      An AVL insert does extra work that a plain BST insert does not. When is a plain BST still a reasonable choice?

      When the keys arrive in random order, a plain BST is usually close to balanced (height about 2–3 times log₂ n) and is simpler. AVL trees earn their keep when the input might be sorted or nearly sorted, or when you need a guaranteed worst case.

      Each node stores a height. Why not just compute heights when needed?

      Computing a subtree's height from scratch visits every node in it, which is O(n). Storing the height lets each node find its own height in O(1) from its children's stored values, which keeps insert at O(log n).