Trees keep data in an order so search is fast. AVL trees keep them balanced. Heaps and spanning trees are tree ideas too.
Open the interactive lessons →Trees: BST and AVL past questions
Contents
- Binary trees: the vocabulary
- Counting nodes, leaves and height
- Binary search trees (BST)
- Tree traversals
- AVL trees: balance, height and node bounds
- 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 word | Meaning |
|---|---|
| root | the top node |
| leaf | a node with no children |
| height | the 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.
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.
| Word | Meaning | In the picture |
|---|---|---|
| root | the top node, it has no parent | 8 |
| parent / child | a node and the node directly below it | 4 is the parent of 2 and 6 |
| leaf | a node with no children | 1, 3, 6, 10, 14 |
| internal node | a node with at least one child | 8, 4, 12, 2 |
| subtree | a node together with everything below it | the subtree at 4 is 4, 2, 6, 1, 3 |
| depth of a node | number of edges from the root down to it | depth of 3 is 3 |
| height of the tree | how tall the tree is, counted in the way the question says (see below) | 4 nodes on the longest path |
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 path | Nodes on it | Height (empty = 0) |
|---|---|---|
| empty tree | 0 | 0 |
| just the root | 1 | 1 |
| 8, 4, 2, 1 | 4 | 4 |
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.
- Longest path: 5, 3, 4.
- That is 3 nodes.
Answer.
3
Common mistake.
Counting edges (2) instead of nodes.
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.
- 3 goes left of 7.
- 5 goes right of 3.
- 4 goes left of 5.
- 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.
- 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.
Check what height counts.
| Step | Method for any exam question |
|---|---|
| 1 | Mark the root. |
| 2 | Mark the leaves. |
| 3 | Check whether height counts nodes or edges. |
| 4 | Measure. |
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 word | Meaning |
|---|---|
| full level | a depth that holds as many nodes as it can |
| chain | a tree where every node has one child |
| complete tree | all levels full except possibly the last, which fills from the left |
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$
| level | 1 | 2 | 3 | 4 | … | h |
|---|---|---|---|---|---|---|
| most nodes on this level | 1 | 2 | 4 | 8 | … | $2^{h-1}$ |
| most nodes up to this level | 1 | 3 | 7 | 15 | … | $2^h-1$ |
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.
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.
- A full tree of height $h$ has $2^h-1$ nodes.
- $2^{8}-1=255$, so $h=8$.
- 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$.
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$ |
|---|---|---|
| 2 | 1 | 3 |
| 3 | 2 | 5 |
| 4 | 3 | 7 |
| 5 | 4 | 9 |
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$.
- $L=6$.
- $N=2\cdot6-1=11$.
- 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.
- If the tree is strictly binary then $N=2L-1$, so $L=(N+1)/2=14$ for $N=27$.
- 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$.
Quick rule for maximum leaves. $n$ nodes give at most $\lceil n/2\rceil$ leaves (11 for 21; 2 for 4).
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.
- A chain of $h$ nodes is a binary tree of height $h$.
- It has exactly one leaf, at the bottom.
Answer.
False: a chain has 1 leaf.
Common mistake.
Testing only full, bushy trees.
Levels double.
| Step | Method for any exam question |
|---|---|
| 1 | Write the level maximum. |
| 2 | Add the levels. |
| 3 | Test 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 word | Meaning |
|---|---|
| binary search tree | a tree where smaller keys go left and larger keys go right |
| search path | the keys compared on the way down |
| successor | the next larger key |
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.
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
The tree is empty, so 8 becomes the root.
3 is smaller, go left from 8.
That spot is empty, so 3 becomes the left child of 8.
10 is larger, go right from 8.
That spot is empty, so 10 becomes the right child of 8.
1 is smaller, go left from 8.
1 is smaller, go left from 3.
That spot is empty, so 1 becomes the left child of 3.
6 is smaller, go left from 8.
6 is larger, go right from 3.
That spot is empty, so 6 becomes the right child of 3.
14 is larger, go right from 8.
14 is larger, go right from 10.
That spot is empty, so 14 becomes the right child of 10.
4 is smaller, go left from 8.
4 is larger, go right from 3.
4 is smaller, go left from 6.
That spot is empty, so 4 becomes the left child of 6.
7 is smaller, go left from 8.
7 is larger, go right from 3.
7 is larger, go right from 6.
That spot is empty, so 7 becomes the right child of 6.
All keys are in. An in-order walk would read
1 3 4 6 7 8 10 14, in increasing order.
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
Delete 8. First find it, as in a search.
8 has two children (3 and 10), so we cannot just cut it out.
Step into the left subtree, at 3.
Keep going right: 6.
Keep going right: 7. It has no right child, so 7 is the largest key below 8.
The old 7 node has at most one child, so removing it is easy.
Write 7 where 8 was. Everything left of it is smaller and everything right is larger, so the BST rule holds.
8 is gone and the in-order list is still sorted. (Using the smallest key of the right subtree, the successor, is equally valid.)
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.
- Compare with 40: 50 is larger, go right.
- Compare with 60: 50 is smaller, go left.
- Compare with 50: found.
- 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?
| step | key | move | allowed interval | inside? |
|---|---|---|---|---|
| 1 | 60 | (root) | $(-\infty,\infty)$ | yes |
| 2 | 20 | left (20<60) | $(-\infty,60)$ | yes |
| 3 | 45 | right (45>20) | $(20,60)$ | yes |
| 4 | 52 | right (52>45) | $(45,60)$ | yes |
| 5 | 41 | left (41<52) | $(45,52)$ | no: 41 is below 45 |
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.
- 25 is the root; 15 goes left and 40 right.
- 10 and 20 go under 15; 30 and 45 go under 40.
- 28 goes 25 → 40 → 30, then left of 30.
- 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.
- The first order fills each level: height 3.
- The sorted order always goes right: height 7.
- 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.
Smaller left, larger right.
| Step | Method for any exam question |
|---|---|
| 1 | Compare with the current node. |
| 2 | Go left if smaller, right if larger. |
| 3 | Stop 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 word | Meaning |
|---|---|
| pre-order | node, left, right |
| in-order | left, node, right |
| post-order | left, right, node |
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)
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.
| Traversal | Output 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
| call stack (oldest first) | output so far | what happens next | |
|---|---|---|---|
| 2 | in(8) → in(4) → in(2) | 2 | no right child: return until an unfinished caller, 4 |
| 4 | in(8) → in(4) | 2 4 | now call the right child, 6 |
| 6 | in(8) → in(4) → in(6) | 2 4 6 | no right child: return until an unfinished caller, 8 |
| 8 | in(8) | 2 4 6 8 | now call the right child, 12 |
| 10 | in(8) → in(12) → in(10) | 2 4 6 8 10 | no right child: return until an unfinished caller, 12 |
| 12 | in(8) → in(12) | 2 4 6 8 10 12 | now call the right child, 14 |
| 14 | in(8) → in(12) → in(14) | 2 4 6 8 10 12 14 | no right child: every call returns, done |
In-order walk with its stack
In-order means left, node, right. The stack remembers the nodes we still owe a visit.
Before printing 8 we must finish its left subtree, so push it and go left.
Before printing 4 we must finish its left subtree, so push it and go left.
Before printing 2 we must finish its left subtree, so push it and go left.
Nothing is left on the left side of 2: pop it and print it.
Nothing is left on the left side of 4: pop it and print it. Then go to its right child 6.
Before printing 6 we must finish its left subtree, so push it and go left.
Nothing is left on the left side of 6: pop it and print it.
Nothing is left on the left side of 8: pop it and print it. Then go to its right child 12.
Before printing 12 we must finish its left subtree, so push it and go left.
Before printing 10 we must finish its left subtree, so push it and go left.
Nothing is left on the left side of 10: pop it and print it.
Nothing is left on the left side of 12: pop it and print it. Then go to its right child 14.
Before printing 14 we must finish its left subtree, so push it and go left.
Nothing is left on the left side of 14: pop it and print it.
The stack is empty. Output
2 4 6 8 10 12 14is 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
Level-order visits the tree row by row. A queue keeps the nodes in the order we found them.
Take 8 from the front and print it. Add its children 4, 12 to the back.
Take 4 from the front and print it. Add its children 2, 6 to the back.
Take 12 from the front and print it. Add its children 10, 14 to the back.
Take 2 from the front and print it. It is a leaf, so nothing joins the queue.
Take 6 from the front and print it. It is a leaf, so nothing joins the queue.
Take 10 from the front and print it. It is a leaf, so nothing joins the queue.
Take 14 from the front and print it. It is a leaf, so nothing joins the queue.
The queue is empty. Level-order output:
8 4 12 2 6 10 14.
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 order | What it prints on a BST |
|---|---|
| left, print, right | increasing order |
| right, print, left | decreasing order |
| print, left, right | pre-order (root first) |
| left, right, print | post-order (root last) |
| right, left, print | mirror 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.
- The right subtree of 6 (rooted at 9) comes first: 10, 8, 7, 9.
- Then the left subtree (rooted at 3): 5, 4, 2, 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.
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.
- The tree has 5 at the root, 3 with children 1 and 4, and 8 on the right.
- Visit the right side first: 8.
- Then the root 5.
- 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.
- Find the position of
printamong 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.
Pre: first. In: middle. Post: last.
| Step | Method for any exam question |
|---|---|
| 1 | Say the rule: where does the node come? |
| 2 | Apply it to the root. |
| 3 | Repeat 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 word | Meaning |
|---|---|
| balance | height of the left subtree minus height of the right |
| AVL tree | a BST where every balance is $-1$, $0$ or $1$ |
| $S(h)$ | the fewest nodes of an AVL tree of height $h$ |
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.
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.
- Root 5. Left: 2 with right child 3, height 2.
- Right: 7 → 9 → 10 → 11 is the longest path, height 4.
- 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.
$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$ |
|---|---|---|---|
| 2 | 1 | 0 | 2 |
| 3 | 2 | 1 | 4 |
| 4 | 4 | 2 | 7 |
| 5 | 7 | 4 | 12 |
| 6 | 12 | 7 | 20 |
| 7 | 20 | 12 | 33 |
| 8 | 33 | 20 | 54 |
| 9 | 54 | 33 | 88 |
| 10 | 88 | 54 | 143 |
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$.
- $N(8)=54\le70$.
- $N(9)=88>70$.
- 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).
- $N(6)=20\le30$ and $N(7)=33>30$.
- So $h=6$.
Answer.
6
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$.
- Minimum $N(8)=54$.
- Maximum $2^8-1=255$.
Answer.
Minimum 54, maximum 255
"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.
- At the root the difference is $3-3=0$.
- At the left child the difference is $2-0=2$.
- One bad node is enough.
Answer.
No.
Common mistake.
Checking only the root.
Every node: heights differ by at most one.
| Step | Method for any exam question |
|---|---|
| 1 | Compute both subtree heights. |
| 2 | Take their difference. |
| 3 | A 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.
| Claim | Verdict | Why |
|---|---|---|
| The path between any two nodes has $O(\log n)$ edges | True | Go 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 subtree | False | Insert $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 number | False | AVL limits the difference in height to 1. Sizes can differ by far more. |
| Leaves are at least as many as internal nodes | False | Insert $5,3,7,2,4,6,1$. This AVL tree has $3$ leaves and $4$ internal nodes. |
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 word | Meaning |
|---|---|
| rotation | a local rearrangement that keeps the BST order |
| unbalanced node | a node whose balance reached 2 or $-2$ |
| double rotation | a rotation at the child followed by one at the node |
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.
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
A balanced AVL tree. Under each node, BF = left height − right height. We insert 10.
Plain BST insert of 10. Walking up, node 40 is the lowest one with BF = +2.
From 40 the path goes left twice (LL): one right rotation at 40.
25, the middle key of the three, is on top. All balance factors here are legal again.
Final AVL tree: height 3 for 6 keys, and the in-order list is still sorted.
LR rotation, live: insert 35
A balanced AVL tree. We insert 35, which will need two rotations.
Plain BST insert of 35. Walking up, node 60 is the lowest one with BF = +2.
From 60 the path goes left then right (LR). First rotate left at the child 30.
40 moved above 30. The path from 60 is now straight (LL).
40, the middle key of the three, is on top. All balance factors here are legal again.
Final AVL tree: height 3 for 6 keys, and the in-order list is still sorted.
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.
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.
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
Insert 40 as in a BST. Every balance factor stays in −1, 0, +1, so no rotation is needed.
Insert 70 as in a BST. Every balance factor stays in −1, 0, +1, so no rotation is needed.
Insert 10 as in a BST. Every balance factor stays in −1, 0, +1, so no rotation is needed.
Insert 30 as in a BST. Every balance factor stays in −1, 0, +1, so no rotation is needed.
Insert 50 as in a BST. Every balance factor stays in −1, 0, +1, so no rotation is needed.
Plain BST insert of 60. Walking up, node 70 is the lowest one with BF = +2.
From 70 the path goes left then right (LR). First rotate left at the child 50.
60 moved above 50. The path from 70 is now straight (LL).
60, the middle key of the three, is on top. All balance factors here are legal again.
Plain BST insert of 20. Walking up, node 10 is the lowest one with BF = -2.
From 10 the path goes right then left (RL). First rotate right at the child 30.
20 moved above 30. The path from 10 is now straight (RR).
20, the middle key of the three, is on top. All balance factors here are legal again.
Insert 80 as in a BST. Every balance factor stays in −1, 0, +1, so no rotation is needed.
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.
- The leaves are 10, 30, 50, 80.
- 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.
- 90 goes right of 75: path 40, 60, 75, then right.
- 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.
- The path from 40 is right, right, so it is an RR case: rotate left at 40.
- 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.
- Inserting 30 unbalances 10: an RR case, so 20 becomes the root.
- Inserting 25 needs no rotation.
- Inserting 28 unbalances 30 along left then right: an LR case.
- 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.
Straight line: one turn. Bend: two turns.
| Step | Method for any exam question |
|---|---|
| 1 | Insert as in a search tree. |
| 2 | Find the lowest unbalanced node. |
| 3 | Name the shape: LL, RR, LR or RL. |
| 4 | Rotate. |