Trees: BST and AVL

Trees keep data in an order so search is fast. AVL trees keep them balanced. Heaps and spanning trees are tree ideas too.

6 lessons · 33 past questions · 102 marks in the papers collected here

Open the interactive lessons →Trees: BST and AVL past questions

Diagrams, animations, quizzes and checked solutions are on the interactive pages.

Contents

  1. Binary trees: the vocabulary
  2. Counting nodes, leaves and height
  3. Binary search trees (BST)
  4. Tree traversals
  5. AVL trees: balance, height and node bounds
  6. AVL insertion and rotations

1. Binary trees: the vocabulary

A binary tree is a family tree where each person has at most two children, a left one and a right one.

What a tree is, the names of its parts, and the two height conventions the exam uses.

The question this lesson answers. What exactly do root, leaf, height and depth mean here?

New wordMeaning
rootthe top node
leafa node with no children
heightthe number of nodes on the longest path from the root down to a leaf

A tree stores data in nodes joined by edges, like a family tree or a folder structure. In a binary tree every node has at most two children, called the left child and the right child.

Picture it

Think of a company chart where every manager has at most two direct reports. The CEO is the root. People with nobody under them are leaves. Everyone else is an internal node.

WordMeaningIn the picture
rootthe top node, it has no parent8
parent / childa node and the node directly below it4 is the parent of 2 and 6
leafa node with no children1, 3, 6, 10, 14
internal nodea node with at least one child8, 4, 12, 2
subtreea node together with everything below itthe subtree at 4 is 4, 2, 6, 1, 3
depth of a nodenumber of edges from the root down to itdepth of 3 is 3
height of the treehow tall the tree is, counted in the way the question says (see below)4 nodes on the longest path
Read this twice

Height has two conventions. The exam always tells you which. Read the sentence.

  • "Height of the empty tree is 0": a tree with one node has height 1, and height counts the nodes on the longest root-to-leaf path.
  • Some books say a single node has height 0 and count edges. Then every height is one smaller.

In every PYQ for this topic the empty tree is 0 and one node is 1. The picture above has height 4 (path 8, 4, 2, 1).

Counting height the exam way

Longest pathNodes on itHeight (empty = 0)
empty tree00
just the root11
8, 4, 2, 144

Worked example: Find the height

Problem.

A tree has root 5, left child 3, and 3 has a right child 4. No other nodes. What is the height (empty tree = 0)?

Idea.

Follow the longest downward path.

  1. Longest path: 5, 3, 4.
  2. That is 3 nodes.

Answer.

3

Common mistake.

Counting edges (2) instead of nodes.

Levels

Levels. Level 1 is the root, level 2 is its children, and so on. A tree of height $h$ has levels $1,2,\dots,h$.

Why it works. Exam answers change by one if a definition is read differently, so fix the convention first.

Worked example: A tree that looks like a list

Problem.

Insert $7,3,5,4$ into an empty binary search tree. Find the height (empty tree $=0$) and the leaves.

Idea.

Follow where each key lands.

  1. 3 goes left of 7.
  2. 5 goes right of 3.
  3. 4 goes left of 5.
  4. Every node has at most one child, so there is one long path.

Answer.

Height $4$; the only leaf is $4$.

Common mistake.

Counting the edges and answering 3.

Tips and tricks
  • Read how height is defined in the question: counting nodes or counting edges changes the answer by 1.
  • With empty height 0, a tree of height $h$ has at least $h$ and at most $2^h-1$ nodes.
  • Test general statements on a straight chain and on a full tree.
Memory line

Check what height counts.

StepMethod for any exam question
1Mark the root.
2Mark the leaves.
3Check whether height counts nodes or edges.
4Measure.

2. Counting nodes, leaves and height

Level 1 holds at most 1 node, level 2 at most 2, level 3 at most 4, and so on, doubling each time.

The formulas linking height, number of nodes and number of leaves, and where each one comes from.

The question this lesson answers. How many nodes and leaves can a tree of a given height hold?

New wordMeaning
full levela depth that holds as many nodes as it can
chaina tree where every node has one child
complete treeall levels full except possibly the last, which fills from the left
Picture it

A family tree where each person has at most two children: counting generations limits how many relatives can exist.

All of these formulas come from one picture: each level can hold at most twice as many nodes as the level above.

Why the maximum is $2^h-1$

level1234…h
most nodes on this level1248…$2^{h-1}$
most nodes up to this level13715…$2^h-1$
Height to nodes

For a binary tree of height $h$ (empty = 0): most nodes $2^h-1$; fewest nodes $h$ (a chain); most leaves $2^{h-1}$; fewest leaves 1.

Why it works. Each level can at most double the previous one, so totals are sums of powers of two.

Nodes to height

Turn it around: with $n$ nodes the smallest possible height is $\lceil\log_2(n+1)\rceil$ and the largest is $n$. A complete binary tree (all levels full except possibly the last, filled left to right) with $n$ nodes has height $\lceil\log_2(n+1)\rceil$.

Worked example: Height of a complete tree with 255 nodes

Problem.

The height of a complete binary tree containing 255 nodes.

Idea.

$255=2^{8}-1$ is exactly a full tree.

  1. A full tree of height $h$ has $2^h-1$ nodes.
  2. $2^{8}-1=255$, so $h=8$.
  3. Check: $\lceil\log_2 256\rceil=8$.

Answer.

8

Common mistake.

Answering 7 by thinking "$\log_2 255\approx 7.99$, round down". Always round up and use $n+1$.

Strictly binary

A binary tree is strictly binary (also called full) if every node has 0 or 2 children. Then $\text{leaves}=\text{internal nodes}+1$, so $N=2L-1$.

Why $N=2L-1$? Each internal node has exactly 2 children. Count children in two ways. Every node except the root is somebody's child, so the number of children is $N-1$. The internal nodes each give 2 children, so it is also $2I$. Hence $N-1=2I$. Since $N=I+L$, we get $I+L-1=2I$, so $I=L-1$ and $N=2L-1$.

Strictly binary tree: leaves to nodes

leaves $L$internal $L-1$total $N=2L-1$
213
325
437
549

Worked example: Strict tree with 6 leaves

Problem.

A BST is strictly binary and has 6 leaves. How many nodes?

Idea.

Use $N=2L-1$.

  1. $L=6$.
  2. $N=2\cdot6-1=11$.
  3. Being a BST adds no extra condition on the shape.

Answer.

11

Common mistake.

Guessing from the number of leaves alone, such as 12. Use the formula.

Worked example: Maximum leaves with 27 nodes

Problem.

The most leaves a binary tree with 27 nodes can have.

Idea.

Leaves are the most when most nodes are leaves, which happens when nearly every internal node has two children.

  1. If the tree is strictly binary then $N=2L-1$, so $L=(N+1)/2=14$ for $N=27$.
  2. Could another shape give more? Count children. There are $N-1=26$ non-root nodes, and each is a child of some internal node. An internal node has at most 2 children, so $2I\ge26$, so $I\ge13$. Then $L=27-I\le14$.

Answer.

14

Common mistake.

Using $27/2=13.5\to13$. For odd $n$ the maximum is $(n+1)/2$.

Exam tip

Quick rule for maximum leaves. $n$ nodes give at most $\lceil n/2\rceil$ leaves (11 for 21; 2 for 4).

Test with the two extremes

Statement checks like "$H-1\le L\le 2^{H-1}$": test a chain. A chain of $H$ nodes has 1 leaf, so for $H\ge3$ the lower bound $H-1$ already fails. A claim "always true" must survive the chain and the full tree.

Worked example: Test the claim on a chain

Problem.

"A binary tree of height $h$ always has at least 2 leaves when $h\ge3$." True or false?

Idea.

Try the most lopsided tree.

  1. A chain of $h$ nodes is a binary tree of height $h$.
  2. It has exactly one leaf, at the bottom.

Answer.

False: a chain has 1 leaf.

Common mistake.

Testing only full, bushy trees.

Memory line

Levels double.

StepMethod for any exam question
1Write the level maximum.
2Add the levels.
3Test with a tiny tree.

3. Binary search trees (BST)

A BST keeps smaller keys on the left and bigger keys on the right of every node, so you can search by repeatedly choosing a side.

The BST rule, how to insert and search by hand, how to test if a sequence could be a path, and the cost of searching.

The question this lesson answers. How does ordering the keys make searching fast?

New wordMeaning
binary search treea tree where smaller keys go left and larger keys go right
search paththe keys compared on the way down
successorthe next larger key
BST rule

BST rule. For every node with key $k$: all keys in its left subtree are smaller than $k$ and all keys in its right subtree are larger. (This is about the whole subtree, not only the children.)

Why it works. Every comparison rules out one whole side of the tree.

Picture it

It is the game "guess my number between 1 and 100" played on a tree. Each node asks "is it lower or higher?" and removes one side.

Insert a key: start at the root. If the key is smaller go left, if larger go right. Keep going until you reach an empty place, and put the new node there. Watch the sequence 8, 3, 10, 1, 6, 14, 4, 7.

BST insertion of 8, 3, 10, 1, 6, 14, 4, 7

  1. The tree is empty, so 8 becomes the root.

  2. 3 is smaller, go left from 8.

  3. That spot is empty, so 3 becomes the left child of 8.

  4. 10 is larger, go right from 8.

  5. That spot is empty, so 10 becomes the right child of 8.

  6. 1 is smaller, go left from 8.

  7. 1 is smaller, go left from 3.

  8. That spot is empty, so 1 becomes the left child of 3.

  9. 6 is smaller, go left from 8.

  10. 6 is larger, go right from 3.

  11. That spot is empty, so 6 becomes the right child of 3.

  12. 14 is larger, go right from 8.

  13. 14 is larger, go right from 10.

  14. That spot is empty, so 14 becomes the right child of 10.

  15. 4 is smaller, go left from 8.

  16. 4 is larger, go right from 3.

  17. 4 is smaller, go left from 6.

  18. That spot is empty, so 4 becomes the left child of 6.

  19. 7 is smaller, go left from 8.

  20. 7 is larger, go right from 3.

  21. 7 is larger, go right from 6.

  22. That spot is empty, so 7 becomes the right child of 6.

  23. All keys are in. An in-order walk would read 1 3 4 6 7 8 10 14, in increasing order.

Notice

The shape of a BST depends on the order of insertion. The same keys inserted in sorted order give a chain.

Delete a node with two children. Replace its key with its inorder predecessor (the largest key in its left subtree), then delete that predecessor, which has at most one child.

Delete 8, a node with two children

  1. Delete 8. First find it, as in a search.

  2. 8 has two children (3 and 10), so we cannot just cut it out.

  3. Step into the left subtree, at 3.

  4. Keep going right: 6.

  5. Keep going right: 7. It has no right child, so 7 is the largest key below 8.

  6. The old 7 node has at most one child, so removing it is easy.

  7. Write 7 where 8 was. Everything left of it is smaller and everything right is larger, so the BST rule holds.

  8. 8 is gone and the in-order list is still sorted. (Using the smallest key of the right subtree, the successor, is equally valid.)

Cost of search

Search follows one root-to-node path, so it costs at most the height. Balanced tree: height $\approx\log_2 n$, so $O(\log n)$. Chain: height $n$, so $O(n)$. Number of comparisons to find a key = number of nodes on the path from the root to it, including the key itself.

Worked example: Comparisons to find 50

Problem.

Keys 40, 25, 60, 10, 30, 50, 70 are inserted into an empty BST. How many comparisons does a search for 50 make?

Idea.

List the nodes on the path.

  1. Compare with 40: 50 is larger, go right.
  2. Compare with 60: 50 is smaller, go left.
  3. Compare with 50: found.
  4. 3 nodes on the path.

Answer.

3

Common mistake.

Counting edges. Comparisons count nodes.

Minimum and maximum. The smallest key is found by going left as far as possible. The largest key is found by going right as far as possible. So the maximum has no right child, but it need not be a leaf (it can have a left child). The maximum is also not always the root.

Height of a BST of height $h$. It has at most $2^h-1$ nodes (full) and at least $h$ nodes (a chain), the same as any binary tree.

Could this be a root-to-leaf path? The bounds method. Every time you move left from a node you get a new upper bound (the next keys must be smaller than that node). Every move right gives a new lower bound. Keep an interval $(low, high)$ and check each new key falls inside it.

Is 60, 20, 45, 52, 41, 48 a valid path?

stepkeymoveallowed intervalinside?
160(root)$(-\infty,\infty)$yes
220left (20<60)$(-\infty,60)$yes
345right (45>20)$(20,60)$yes
452right (52>45)$(45,60)$yes
541left (41<52)$(45,52)$no: 41 is below 45
Shortcut

A faster check: every later key must respect every earlier turn. After going right of $x$, later keys are bigger than $x$; after going left of $y$, they are smaller than $y$. In 60, 20, 45, 52, 41: you went right of 45, but 41 < 45.

k-th smallest. The in-order traversal of a BST lists keys in increasing order (next section). The k-th smallest is the k-th key in that list.

Worked example: Height from an insertion order

Problem.

Insert 25, 15, 40, 10, 20, 30, 45, 28. What is the height (empty tree = 0)?

Idea.

Place each key and watch the deepest path.

  1. 25 is the root; 15 goes left and 40 right.
  2. 10 and 20 go under 15; 30 and 45 go under 40.
  3. 28 goes 25 → 40 → 30, then left of 30.
  4. The longest path has 4 nodes.

Answer.

4

Common mistake.

Forgetting the last key, which here creates the longest path.

Worked example: Same keys, different trees

Problem.

Insert $4,2,6,1,3,5,7$ into one empty tree and $1,2,3,4,5,6,7$ into another. Compare their heights and in-order lists.

Idea.

The order of insertion fixes the shape.

  1. The first order fills each level: height 3.
  2. The sorted order always goes right: height 7.
  3. In-order reads keys in increasing order in both.

Answer.

Heights $3$ and $7$; the in-order lists are identical.

Common mistake.

Thinking the same keys always give the same tree.

Memory line

Smaller left, larger right.

StepMethod for any exam question
1Compare with the current node.
2Go left if smaller, right if larger.
3Stop on a match or an empty place.

4. Tree traversals

A traversal is a rule for visiting every node exactly once. The three rules differ only in when you print the node.

The three depth-first orders, how to read traversal code, and the reverse variants that print a BST in decreasing order.

The question this lesson answers. In which order are the nodes visited?

New wordMeaning
pre-ordernode, left, right
in-orderleft, node, right
post-orderleft, right, node
Picture it

Touring a house with two doors in every room: you may describe a room before, between or after visiting what lies behind its doors.

In-order: left, node, right

def inorder(t):
    if t is not None:
        inorder(t.left)
        print(t.value, end=" ")
        inorder(t.right)
The three orders

Pre-order: node, left, right. In-order: left, node, right. Post-order: left, right, node. Only the position of print changes. The word tells you when the node itself is visited relative to its subtrees.

Why it works. All three orders walk the same path; they differ only in when the node itself is recorded.

TraversalOutput on this tree
pre-order (node, left, right)8 4 2 6 12 10 14
in-order (left, node, right)2 4 6 8 10 12 14
post-order (left, right, node)2 6 4 10 14 12 8
reverse in-order (right, node, left)14 12 10 8 6 4 2

What the recursion does. A call in(x) first finishes the whole left subtree, then prints x, then handles the right subtree. A caller waits on the call stack while this happens. Each row below is the moment of one print.

In-order on the tree above: the call stack at each print

printcall stack (oldest first)output so farwhat happens next
2in(8) → in(4) → in(2)2no right child: return until an unfinished caller, 4
4in(8) → in(4)2 4now call the right child, 6
6in(8) → in(4) → in(6)2 4 6no right child: return until an unfinished caller, 8
8in(8)2 4 6 8now call the right child, 12
10in(8) → in(12) → in(10)2 4 6 8 10no right child: return until an unfinished caller, 12
12in(8) → in(12)2 4 6 8 10 12now call the right child, 14
14in(8) → in(12) → in(14)2 4 6 8 10 12 14no right child: every call returns, done

In-order walk with its stack

  1. In-order means left, node, right. The stack remembers the nodes we still owe a visit.

  2. Before printing 8 we must finish its left subtree, so push it and go left.

  3. Before printing 4 we must finish its left subtree, so push it and go left.

  4. Before printing 2 we must finish its left subtree, so push it and go left.

  5. Nothing is left on the left side of 2: pop it and print it.

  6. Nothing is left on the left side of 4: pop it and print it. Then go to its right child 6.

  7. Before printing 6 we must finish its left subtree, so push it and go left.

  8. Nothing is left on the left side of 6: pop it and print it.

  9. Nothing is left on the left side of 8: pop it and print it. Then go to its right child 12.

  10. Before printing 12 we must finish its left subtree, so push it and go left.

  11. Before printing 10 we must finish its left subtree, so push it and go left.

  12. Nothing is left on the left side of 10: pop it and print it.

  13. Nothing is left on the left side of 12: pop it and print it. Then go to its right child 14.

  14. Before printing 14 we must finish its left subtree, so push it and go left.

  15. Nothing is left on the left side of 14: pop it and print it.

  16. The stack is empty. Output 2 4 6 8 10 12 14 is in increasing order because this is a BST.

Level-order (row by row) is the common walk that uses a queue instead of recursion.

Level-order walk with its queue

  1. Level-order visits the tree row by row. A queue keeps the nodes in the order we found them.

  2. Take 8 from the front and print it. Add its children 4, 12 to the back.

  3. Take 4 from the front and print it. Add its children 2, 6 to the back.

  4. Take 12 from the front and print it. Add its children 10, 14 to the back.

  5. Take 2 from the front and print it. It is a leaf, so nothing joins the queue.

  6. Take 6 from the front and print it. It is a leaf, so nothing joins the queue.

  7. Take 10 from the front and print it. It is a leaf, so nothing joins the queue.

  8. Take 14 from the front and print it. It is a leaf, so nothing joins the queue.

  9. The queue is empty. Level-order output: 8 4 12 2 6 10 14.

Notice

In-order on a BST gives the keys in increasing order. To print in decreasing order, swap the two recursive calls: visit right, print the node, then visit left (reverse in-order).

Reverse in-order: prints a BST in decreasing order

def traverse(t):
    if t is None:
        return
    traverse(t.right)
    print(t.key)
    traverse(t.left)
Code orderWhat it prints on a BST
left, print, rightincreasing order
right, print, leftdecreasing order
print, left, rightpre-order (root first)
left, right, printpost-order (root last)
right, left, printmirror post-order: the reverse of this tree's pre-order

Worked example: Right, left, then print

Problem.

In the tree shown, a function calls itself on the right child, then on the left child, then prints the node. What is printed?

Idea.

Finish the whole right subtree, then the whole left subtree, then the node itself.

  1. The right subtree of 6 (rooted at 9) comes first: 10, 8, 7, 9.
  2. Then the left subtree (rooted at 3): 5, 4, 2, 3.
  3. Finally the root 6.

Answer.

10 8 7 9 5 4 2 3 6

Common mistake.

Reading it as ordinary post-order, which would start on the left.

Which traversal gives 20, 12, 9, 15, 30, 25, 40 on a BST? The first key is the root (20), then the whole left subtree (12, 9, 15), then the right subtree (30, 25, 40). The root is printed first, so this is pre-order. In-order of a BST would be sorted, which this is not.

Post-order: the root is last. If you are given a post-order list, the last key is the root. That helps you rebuild the tree.

Trap

Do not memorise outputs. Draw the tree, then for each node write what is printed before its subtrees, between them and after them.

Worked example: Swapping the recursive calls

Problem.

For the tree built from $5,3,8,1,4$, a function visits right, then prints the node, then visits left. What is printed?

Idea.

This is in-order, mirrored.

  1. The tree has 5 at the root, 3 with children 1 and 4, and 8 on the right.
  2. Visit the right side first: 8.
  3. Then the root 5.
  4. Then the left side, right first: 4, 3, 1.

Answer.

$8,5,4,3,1$

Common mistake.

Printing the pre-order list 5, 3, 1, 4, 8.

Tips and tricks
  • Find the position of print among the two recursive calls: before, between or after.
  • In pre-order the root comes first; in post-order it comes last. Use this to remove options.
  • For a BST, in-order must come out sorted. If it does not, you made a slip.
Memory line

Pre: first. In: middle. Post: last.

StepMethod for any exam question
1Say the rule: where does the node come?
2Apply it to the root.
3Repeat inside each subtree.

5. AVL trees: balance, height and node bounds

An AVL tree is a BST that keeps itself nearly balanced, so its height always stays small.

What "height-balanced" means, how to compute slopes, and the minimum and maximum number of nodes for a given height.

The question this lesson answers. How is a search tree kept short?

New wordMeaning
balanceheight of the left subtree minus height of the right
AVL treea BST where every balance is $-1$, $0$ or $1$
$S(h)$the fewest nodes of an AVL tree of height $h$
AVL tree

The slope (balance factor) of a node is the absolute difference between the heights of its left and right subtrees. An AVL tree is a BST in which every node has slope 0 or 1. If a node ever gets slope 2, the tree rotates to fix it (next section).

Why it works. Limiting the height difference at every node forces the number of nodes to grow quickly with height.

Picture it

A see-saw with weights: the two sides may differ by at most one level, otherwise it tips and must be rebalanced.

Computing a slope. Take the heights of the two subtrees (empty = 0) and subtract. In the tree below each node shows its balance factor (left height minus right height).

Worked example: Slope of the root of a plain BST

Problem.

Insert 5, 2, 3, 7, 9, 8, 10, 11 with no rotations. What is |height(left) − height(right)| at the root?

Idea.

Build the tree and measure both sides.

  1. Root 5. Left: 2 with right child 3, height 2.
  2. Right: 7 → 9 → 10 → 11 is the longest path, height 4.
  3. Slope = |2 − 4| = 2.

Answer.

2

Common mistake.

Using the height of the whole tree, or counting edges.

Smallest AVL tree of height $h$. To make the tree as small as possible while keeping height $h$, give the root one subtree of height $h-1$ (as small as possible) and the other of height $h-2$ (as small as possible), because both being $h-1$ would use more nodes.

Minimum nodes recurrence

$N(h)=N(h-1)+N(h-2)+1$ with $N(0)=0$, $N(1)=1$. (the +1 is the root.)

Minimum nodes of an AVL tree of height h (empty = 0)

height $h$$N(h-1)$$N(h-2)$$N(h)=N(h-1)+N(h-2)+1$
2102
3214
4427
57412
612720
7201233
8332054
9543388
108854143
Both bounds

AVL tree of height $h$: $\;N(h)\le n\le 2^h-1$. Maximum nodes is the same as any binary tree. Therefore $h\le 1.44\log_2 n$: an AVL tree is always $O(\log n)$ tall.

Worked example: Maximum height of an AVL tree with 70 nodes

Problem.

An AVL tree contains 70 nodes (empty tree = height 0).

Idea.

The tallest AVL tree with $n$ nodes is the one that uses the minimum nodes per height. Find the largest $h$ with $N(h)\le n$.

  1. $N(8)=54\le70$.
  2. $N(9)=88>70$.
  3. So the largest height is 8.

Answer.

8

Common mistake.

Using $\log_2 70\approx6$. A logarithm estimates the smallest height, not the largest.

Worked example: Maximum height with 30 nodes

Problem.

An AVL tree contains 30 nodes (empty tree = height 0).

  1. $N(6)=20\le30$ and $N(7)=33>30$.
  2. So $h=6$.

Answer.

6

Which table?

Pick the right end of the table. Question says "maximum height with $n$ nodes" → use minimum-node table $N(h)$. Question says "minimum height" → use $\lceil\log_2(n+1)\rceil$. Question says "minimum nodes for height $h$" → read $N(h)$ directly.

Worked example: Min and max nodes of height 8

Problem.

An AVL tree of height 8 (empty tree = 0).

Idea.

Min from the table, max from $2^h-1$.

  1. Minimum $N(8)=54$.
  2. Maximum $2^8-1=255$.

Answer.

Minimum 54, maximum 255

Trap

"For any node, size of left subtree minus size of right subtree is at most 3" is false for AVL: the slope limit is on heights, not sizes. Example: a perfect left subtree of height 4 has 15 nodes and a minimal right subtree of height 3 has 4 nodes. Heights differ by 1 (allowed), but the sizes differ by 11.

Worked example: Balanced at the top is not enough

Problem.

A root has two subtrees of equal height 3. Its left child has a left subtree of height 2 and an empty right subtree. Is the tree an AVL tree?

Idea.

The rule applies at every node.

  1. At the root the difference is $3-3=0$.
  2. At the left child the difference is $2-0=2$.
  3. One bad node is enough.

Answer.

No.

Common mistake.

Checking only the root.

Memory line

Every node: heights differ by at most one.

StepMethod for any exam question
1Compute both subtree heights.
2Take their difference.
3A difference above one breaks the rule.

"Which statement is always true?" for an AVL tree

Start from the one fact you can trust: the height is $O(\log n)$. Then test each claim.

ClaimVerdictWhy
The path between any two nodes has $O(\log n)$ edgesTrueGo up to their lowest shared ancestor, then down. Each part is shorter than the height, so the path is at most twice the height.
Each node is the median of its subtreeFalseInsert $3,1,5,6,7$. The root is $3$, but the median of $\{1,3,5,6,7\}$ is $5$.
Left and right subtree sizes differ by at most a small numberFalseAVL limits the difference in height to 1. Sizes can differ by far more.
Leaves are at least as many as internal nodesFalseInsert $5,3,7,2,4,6,1$. This AVL tree has $3$ leaves and $4$ internal nodes.
How to attack it

For any claim other than height, search order or balance, try to build a small counterexample. AVL promises only those.

6. AVL insertion and rotations

Insert like a normal BST. If some node tips over (slope 2), twist the three nodes around it back into balance.

The four rotation cases, how to find the node to fix, and how to build an AVL tree by hand.

The question this lesson answers. What do you do when an insertion unbalances the tree?

New wordMeaning
rotationa local rearrangement that keeps the BST order
unbalanced nodea node whose balance reached 2 or $-2$
double rotationa rotation at the child followed by one at the node
Picture it

A hanging mobile that tilts: move one joint up and the whole thing levels again without changing the left-to-right order.

Procedure. (1) Insert the key exactly as in a BST. (2) Walk back up from the new node. (3) Find the lowest node whose slope became 2. (4) Look at the path from that node down towards the new key: two steps (left or right each time). That pair of directions tells you the case. (5) Apply the rotation. After one fix the whole tree is balanced again.

The four cases

LL (left, left): rotate right at the unbalanced node. RR (right, right): rotate left. LR (left, then right): rotate left at the child, then right at the node. RL (right, then left): rotate right at the child, then left at the node.

Why it works. A rotation changes which node is on top while keeping the left-to-right order of the keys.

Each picture shows the unbalanced tree and the result. Labels show bf = left height minus right height.

LL rotation, live: insert 10

  1. A balanced AVL tree. Under each node, BF = left height − right height. We insert 10.

  2. Plain BST insert of 10. Walking up, node 40 is the lowest one with BF = +2.

  3. From 40 the path goes left twice (LL): one right rotation at 40.

  4. 25, the middle key of the three, is on top. All balance factors here are legal again.

  5. Final AVL tree: height 3 for 6 keys, and the in-order list is still sorted.

LR rotation, live: insert 35

  1. A balanced AVL tree. We insert 35, which will need two rotations.

  2. Plain BST insert of 35. Walking up, node 60 is the lowest one with BF = +2.

  3. From 60 the path goes left then right (LR). First rotate left at the child 30.

  4. 40 moved above 30. The path from 60 is now straight (LL).

  5. 40, the middle key of the three, is on top. All balance factors here are legal again.

  6. Final AVL tree: height 3 for 6 keys, and the in-order list is still sorted.

The same rotation on a big tree

Real exam trees have subtrees hanging off the three nodes. For an LL case at $z$, with left child $y$, call the subtrees $T_1, T_2, T_3$:

  • before: $z$ has left child $y$ (children $T_1$, $T_2$) and right subtree $T_3$;
  • after a right rotation: $y$ has left subtree $T_1$ and right child $z$ (children $T_2$, $T_3$).

Only $T_2$ changes parent: it moves from $y$'s right to $z$'s left.

Why it is still a search tree. In-order, both shapes read $T_1,\ y,\ T_2,\ z,\ T_3$, so no key changes its place in sorted order. Why one rotation is enough. After the insertion $T_1$ has height $h+1$ and $T_2,T_3$ have height $h$. After rotating, $z$ has height $h+1$ and $y$ has height $h+2$, the height this subtree had before the insertion, so nothing higher up becomes unbalanced.

Shortcut: median of three

Result rule that saves time. In every case the middle key of the three nodes (by value) becomes the new top, with the smaller key on its left and the larger key on its right. Subtrees hanging off these nodes keep their left-to-right order and are re-attached.

Trap

Fix the lowest unbalanced node, not the root. Check slopes from the new leaf upwards; the first node with slope 2 is the one.

Worked build: insert 40, 70, 10, 30, 50, 60, 20, 80 into an empty AVL tree. Before each step, predict whether a rotation is needed. The newest key is highlighted.

AVL insertion of 40, 70, 10, 30, 50, 60, 20, 80

  1. Insert 40 as in a BST. Every balance factor stays in −1, 0, +1, so no rotation is needed.

  2. Insert 70 as in a BST. Every balance factor stays in −1, 0, +1, so no rotation is needed.

  3. Insert 10 as in a BST. Every balance factor stays in −1, 0, +1, so no rotation is needed.

  4. Insert 30 as in a BST. Every balance factor stays in −1, 0, +1, so no rotation is needed.

  5. Insert 50 as in a BST. Every balance factor stays in −1, 0, +1, so no rotation is needed.

  6. Plain BST insert of 60. Walking up, node 70 is the lowest one with BF = +2.

  7. From 70 the path goes left then right (LR). First rotate left at the child 50.

  8. 60 moved above 50. The path from 70 is now straight (LL).

  9. 60, the middle key of the three, is on top. All balance factors here are legal again.

  10. Plain BST insert of 20. Walking up, node 10 is the lowest one with BF = -2.

  11. From 10 the path goes right then left (RL). First rotate right at the child 30.

  12. 20 moved above 30. The path from 10 is now straight (RR).

  13. 20, the middle key of the three, is on top. All balance factors here are legal again.

  14. Insert 80 as in a BST. Every balance factor stays in −1, 0, +1, so no rotation is needed.

  15. Final AVL tree: height 4 for 8 keys, and the in-order list is still sorted.

Worked example: Sum of the leaves

Problem.

After all the insertions above, what is the sum of the keys in the leaf nodes?

Idea.

Read the leaves from the final tree only.

  1. The leaves are 10, 30, 50, 80.
  2. Sum = 10 + 30 + 50 + 80 = 170.

Answer.

170

Common mistake.

Using a tree from before the last rotation.

Worked example: Insert 90 into a small AVL tree

Problem.

AVL tree with root 40, left child 25, right child 60 (children 50 and 75). Insert 90.

Idea.

Find the lowest node with slope 2.

  1. 90 goes right of 75: path 40, 60, 75, then right.
  2. Slopes: 75 has slope 1; 60 has left height 1, right height 2: slope 1; 40 has left height 1, right height 3: slope 2.
  3. The path from 40 is right, right, so it is an RR case: rotate left at 40.
  4. 60 becomes the root, 40 (with 25 and 50) its left, 75 (with child 90) its right.

Answer.

root 60; left 40 (25, 50); right 75 (child 90)

Worked example: Two repairs in one sequence

Problem.

Insert $10,20,30,25,28$ into an empty AVL tree. Which rotations happen, and what is the pre-order list at the end?

Idea.

Repair at the lowest unbalanced node after each insertion.

  1. Inserting 30 unbalances 10: an RR case, so 20 becomes the root.
  2. Inserting 25 needs no rotation.
  3. Inserting 28 unbalances 30 along left then right: an LR case.
  4. 28 rises, with 25 on its left and 30 on its right.

Answer.

RR then LR; pre-order $20,10,28,25,30$.

Common mistake.

Rotating at the root for the second repair.

Memory line

Straight line: one turn. Bend: two turns.

StepMethod for any exam question
1Insert as in a search tree.
2Find the lowest unbalanced node.
3Name the shape: LL, RR, LR or RL.
4Rotate.

Practise this topic →

Other PDSA topics