algoritmauzmanı
Sign in
TREN
7.5Exam Practice
Lesson 7.5.1

Heaps and balanced trees: exam questions and answers

This page is the exam practice for the heaps and balanced trees section. Exams ask about these topics in a few recurring ways: array indexes, whether an array is a heap, insert and remove traces, heapify and heap sort, balance factors and AVL rotations, red-black rules and insertion, B-tree splits and choosing between structures. Here you get original questions of each kind with step-by-step answers.

What you will learn
  • How to write heap index, insert, remove, heapify and heap sort traces without mistakes
  • How to trace insertion and deletion in AVL and red-black trees and decide on rotations and recolouring
  • How B-tree splits work, the bounds on keys and height, and which structure to pick when
30 min

1Heaps: concepts and indexes

The questions are original, but their types were picked from the kinds that often appear in published midterm and final exams and exercise sheets of universities in Turkey and abroad. Solve each question yourself first, then open the box and compare. Unless stated otherwise the heap is a and the array starts at 0; the names match the lessons on the array heap and AVL trees. Writing the tree and the array down at every step is the shortest way to avoid mistakes in these questions.

1In a heap of 20 elements stored in an array starting at 0: at which indexes are the children of index 6? Where is the parent of index 17? At which index is the last inner node, and which range holds the leaves? What would the formulas be if the array started at 1?Midterm · concept

In an array starting at 0, the children of index i are at 2i + 1 and 2i + 2, and its parent is at (i - 1) / 2 (integer division).

  • The children of 6: 2·6 + 1 = 13 and 2·6 + 2 = 14.
  • The parent of 17: (17 - 1) / 2 = 8. Check: the children of 8 are 17 and 18.
  • The last inner node is the parent of the last element (19): (19 - 1) / 2 = 9, that is n/2 - 1. The leaves are at 10 to 19: half of the elements are leaves.
  • If the array starts at 1, the children are at 2i and 2i + 1 and the parent at i / 2. Always say where the array starts in an exam.
2Which of these arrays is a min-heap? A = [2, 5, 3, 9, 6, 4, 8, 10, 12, 7], B = [3, 5, 8, 9, 6, 10, 12, 4, 11].Midterm · concept

For every i ≥ 1 you check that the value at the parent (i - 1) / 2 is not larger than the value at i. The array does not have to be sorted; only parents and children are compared.

  • A is a heap. Parents and children: 2 → 5, 3; 5 → 9, 6; 3 → 4, 8; 9 → 10, 12; 6 → 7. No parent is larger than its child.
  • B is not a heap. The parent of 4 at index 7 is 9 at index 3, and 9 > 4. All other pairs are fine; a single broken pair is enough.
411965101283
Array B drawn as a tree: 9 and its child 4 break the heap rule.
3In a min-heap of 15 distinct values, at which indexes can the second smallest value be? Where can the largest value be? How many elements does a heap of height h have at least and at most?Midterm · concept

The second smallest value is a child of the root: at index 1 or 2. Every value other than the root has a smaller parent; the only value that can be the parent of the second smallest is the root.

The largest value cannot have a child, because the child would have to be larger. So the largest value is in a leaf: at one of the indexes from 15 / 2 = 7 to 14. That is why finding the largest value in a min-heap means looking at about n/2 leaves: O(n).

A heap is a complete tree, so at height h the upper h levels are full and the last level has at least 1 element: at least 2^h and at most 2^(h+1) - 1 elements. From this the height of a heap with n elements is ⌊log₂ n⌋.

2Heaps: traces and code

415, 8, 20, 3, 10, 5, 1 are inserted in order into an empty min-heap. Write the array after each insertion. Then remove the minimum twice and write the array.Midterm · trace

Insert: the value goes to the end of the array and swaps with its parent as long as it is smaller ().

InsertedSift upArray
15none[15]
88 < 15, swap[8, 15]
2020 > 8, stops[8, 15, 20]
33 < 15, swap; 3 < 8, swap[3, 8, 20, 15]
1010 > 8, stops[3, 8, 20, 15, 10]
55 < 20, swap; 5 > 3, stops[3, 8, 5, 15, 10, 20]
11 < 5, swap; 1 < 3, swap[1, 8, 3, 15, 10, 20, 5]

Remove the minimum: the root is taken, the last element is written to the root and swaps with its smaller child as long as it is larger ().

  • 1 comes out. The last element 5 goes to the root: [5, 8, 3, 15, 10, 20]. Its children are 8 and 3; the smaller is 3, swap: [3, 8, 5, 15, 10, 20].
  • 3 comes out. The last element 20 goes to the root: [20, 8, 5, 15, 10]. The smaller child is 5, swap: [5, 8, 20, 15, 10]. 20 is now at index 2 and has no children: [5, 8, 20, 15, 10].
15108205
The heap after two removals: [5, 8, 20, 15, 10].
5The array [9, 4, 7, 1, 8, 2, 6, 3] is turned into a min-heap bottom-up (heapify). Write the array after each inner node is processed. How many swaps are made in total?Final · trace

sifts down every index from the last inner node (8 / 2 - 1 = 3) back to the root. Leaves are already heaps on their own.

IndexWhat happenedArray
3 (1)Its child is 3; 1 is smaller, no swap.[9, 4, 7, 1, 8, 2, 6, 3]
2 (7)Its children are 2 and 6; swap with 2.[9, 4, 2, 1, 8, 7, 6, 3]
1 (4)Its children are 1 and 8; swap with 1. Further down, 4 swaps once more with its child 3.[9, 1, 2, 3, 8, 7, 6, 4]
0 (9)Smaller child 1, swap; then 3, swap; then 4, swap.[1, 3, 2, 4, 8, 7, 6, 9]

In total 0 + 1 + 2 + 3 = 6 swaps. Inserting the same values one by one into an empty heap also gives a heap, but usually a different array, and it takes O(n log n); the bottom-up build takes O(n) because most nodes are near the bottom and move down only a little.

6Sort [5, 13, 2, 25, 7, 17] in ascending order with heap sort. Write the max-heap that is built first, then the array after each step.Final · trace

For ascending order builds a in place. Building starts at index 6 / 2 - 1 = 2: 2 swaps with its child 17; 13 swaps with its child 25; the 5 at the root swaps first with 25, then with 13. Max-heap: [25, 13, 17, 5, 7, 2].

Then at each step the root swaps with the last element of the heap, the heap shrinks by one and the value that came to the root is sifted down. Right of the bar is the sorted part.

StepArray
25 to the end[17, 13, 2, 5, 7 | 25]
17 to the end[13, 7, 2, 5 | 17, 25]
13 to the end[7, 5, 2 | 13, 17, 25]
7 to the end[5, 2 | 7, 13, 17, 25]
5 to the end[2 | 5, 7, 13, 17, 25]

Result: [2, 5, 7, 13, 17, 25]. For example, in the first step 25 and 2 swap: [2, 13, 17, 5, 7 | 25]; the larger child of 2 is 17, swap: [17, 13, 2, 5, 7 | 25].

7A student wrote the sift up function of a min-heap as below. What is the array after inserting 3, 8, 5 into an empty heap? What is the bug and what does it cause?Midterm · code reading

The comparison in the condition is reversed: the value moves up as long as it is larger than its parent. 3 is inserted: [3]. 8 is inserted; 3 < 8, so they swap: [8, 3]. 5 is inserted; its parent is 8 and 8 < 5 is false, so it stops: [8, 3, 5].

void siftUp(struct Heap* h, int i) {    while (i > 0 && h->items[parent(i)] < h->items[i]) {        swap(h, i, parent(i));        i = parent(i);    }}

This function builds a max-heap: the largest value sits at the root and remove-min actually returns the largest. Also, sift down still works with the min-heap rule, so the two functions undo each other. The fix: write > instead of <.

8Write a function that returns whether an integer array of n elements is a min-heap. What is its complexity?Final · code writing

Comparing each child with its parent is enough: for every i from 1 to n - 1, if the value at the parent (i - 1) / 2 is larger, it is not a heap. Each element is compared once: O(n) time, O(1) extra memory. An empty array and a single-element array are heaps.

bool isHeap(int arr[], int n) {    for (int i = 1; i < n; i++) {        if (arr[(i - 1) / 2] > arr[i])     // parent larger than its child            return false;    }    return true;}
def is_heap(arr):    for i in range(1, len(arr)):        if arr[(i - 1) // 2] > arr[i]:     # parent larger than its child            return False    return True
9What is the worst-case time of these operations on a min-heap of n elements: insert, remove the minimum, peek at the minimum, search for an arbitrary value, build a heap from an array, heap sort, remove the k smallest values in order?Midterm · complexity

The height is ⌊log₂ n⌋, so a single sift takes at most O(log n) steps.

OperationTimeWhy
InsertO(log n)One sift up
Remove the minimumO(log n)One sift down
PeekO(1)It is at the root
Search for any valueO(n)A heap is not sorted; every place is checked
Build from an arrayO(n)Most nodes move down only a little
Heap sortO(n log n)n removals
k smallest valuesO(n + k log n)Build plus k removals

3AVL trees

10Which of the two trees below is an AVL tree? Give the balance factor of each node.Midterm · concept

The is the height of the left subtree minus the height of the right subtree; an empty tree has height -1. The tree is AVL only if this difference is -1, 0 or 1 at every node; checking the root alone is not enough.

102040306090807050
Tree A.
1025203060807050
Tree B: the root looks balanced, but 30 is not.
  • A is AVL. Leaves 0; 20: 0 - (-1) = 1; 30: 1 - 0 = 1; 80: -1 - 0 = -1; 70: 0 - 1 = -1; 50: 2 - 2 = 0.
  • B is not AVL. 20: 0 - 0 = 0; 30: 1 - (-1) = 2; 70: 0; root 50: 2 - 1 = 1. The root is fine, but the balance factor of 30 is 2.
1150, 25, 10, 5, 7, 3, 30, 20, 8, 15 are inserted in order into an empty AVL tree. Which insertions cause which rotation? Draw the final tree.Midterm · trace

After each insertion you check balance factors from the new node up to the root; at the first unbalanced node you identify the case (LL, LR, RR, RL) and apply the rotation. In the table a tree is written as root(left, right); "—" is an empty child.

InsertedRotationTree
50, 25none50(25, —)
10LL at 50: right rotation25(10, 50)
5none25(10(5, —), 50)
7LR at 10: left at 5, right at 1025(7(5, 10), 50)
3LL at 25: right rotation7(5(3, —), 25(10, 50))
30, 20, 8none7(5(3, —), 25(10(8, 20), 50(30, —)))
15RL at 7: right at 25, left at 710(7(5(3, —), 8), 25(20(15, —), 50(30, —)))

The last insertion needs the most care: 15 goes to the left of 20. The balance factor of 25 becomes 2 - 1 = 1, but that of 7 is 1 - 3 = -2. The unbalanced node is 7, the heavy side is the right, and the right child 25 leans left: RL. Preorder: 10 7 5 3 8 25 20 15 50 30.

3587152030502510
The final AVL tree.
123 is inserted into the AVL tree below. Which node becomes unbalanced first, and which rotation is applied? Draw the new tree.Final · trace

3 goes to the left of 5. Looking upward: the balance factor of 5 is 1, of 10 is 2 - 0 = 1, of 20 is 2 - 1 = 1; all fine. At the root 40 the left height is 3 and the right height 1: balance factor 2. The unbalanced node is the root.

515102535302050706040
The tree before the insertion.

The heavy side is the left and the left child 20 also leans left (+1): LL, one right rotation at the root. 20 becomes the root and 20's right subtree, 30, moves to the left of 40. After the rotation the height is 3, as before the insertion.

3515102535305070604020
After inserting 3 and rotating right at the root.
1340 is deleted from both trees: (a) 30(20(—, 25), 40), (b) 30(20(10, 25), 40). Which rotation is applied in each, and what is the result?Final · trace

In both, deleting 40 empties the right of 30 and its balance factor becomes 2. The difference is in the balance factor of the left child 20.

  • (a) The balance factor of 20 is -1: it leans right, LR. First rotate left at 20, then right at 30: 25(20, 30).
  • (b) The balance factor of 20 is 0. This never happens after an insertion but can after a deletion. One right rotation (as in LL) is enough: 20(10, 30(25, —)). A double rotation here is wrong; the tree would stay unbalanced.
1025204030
Tree (b) before the deletion.

In a deletion a rotation can lower the height of a subtree by one and the imbalance can move upward, so a deletion may do up to O(log n) rotations on the way to the root. In an insertion one (single or double) rotation is enough.

14How many nodes does an AVL tree of height h have at least? Write a function that computes it. What is the largest possible height of an AVL tree with 20 nodes?Final · code writing

In an AVL tree with the fewest nodes, one subtree of the root has height h - 1 and the other h - 2, and both have the fewest nodes. So N(h) = 1 + N(h - 1) + N(h - 2), N(0) = 1, N(-1) = 0.

h0123456
N(h)1247122033
int minNodes(int h) {    if (h < 0) return 0;          // empty tree    if (h == 0) return 1;         // a single node    return 1 + minNodes(h - 1) + minNodes(h - 2);}

Since N(5) = 20 and N(6) = 33, with 20 nodes the height is at most 5; height 6 needs at least 33 nodes. The same 20 nodes perfectly balanced would have height 4. N(h) grows like the Fibonacci numbers, which shows that the height of an AVL tree is bounded by about 1.44·log₂ n. The recursive function computes the same values again and again; for large h a loop that keeps the last two values is faster.

4Red-black trees

15Which of the three trees below are valid red-black trees? Which rule is broken in the invalid ones? (Orange nodes are red; NIL leaves are black.)Midterm · concept

Check in this order: is the root black, are two reds one under the other, and does every path from the root to a NIL have the same number of black nodes.

5R10B30B20B
Tree a.
5R10R30R20B
Tree b.
5B10B30B20B
Tree c.
  • a is valid. The root is black, the only red node is 5 and its children are NIL. Every path has 2 black nodes (counting the root): 20-10, 20-30.
  • b is invalid. The child 5 of the red 10 is red too: the children of a red node must be black. The black counts are equal (only 20 on every path).
  • c is invalid. The colour rule holds, but the path 20-10-5 has 3 black nodes and the path 20-30 has 2. A tree with only black nodes is valid only if it is a perfect binary tree.
1610, 20, 30, 40, 50, 25 are inserted in order into an empty red-black tree. Which case happens at each insertion? Draw the final tree.Final · trace

A new node enters red. If the parent is red, look at the uncle: if the uncle is red, recolour; if it is black (NIL included), rotate. The details are in the red-black insertion lesson.

InsertedCaseTree (B black, R red)
10Root: painted black.10B
20The parent is black; nothing to do.10B(—, 20R)
30Parent 20 is red, the uncle NIL is black, straight line: rotate left at 10, 20 black, 10 red.20B(10R, 30R)
40Parent 30 is red, uncle 10 is red: recolour. 20 is the root, so it stays black.20B(10B, 30B(—, 40R))
50Parent 40 is red, the uncle is NIL: rotate left at 30.20B(10B, 40B(30R, 50R))
25Parent 30 is red, uncle 50 is red: recolour; 40 turns red, its parent 20 is black, stop.20B(10B, 40R(30B(25R, —), 50B))
10B25R30B50B40R20B
The final tree. Every path to a NIL has 2 black nodes.
17What is the largest possible height of an AVL tree and of a red-black tree with 1,000,000 keys? Can every AVL tree be coloured as a red-black tree? Is every red-black tree an AVL tree?Final · concept

The height of an AVL tree is bounded by about 1.44·log₂ n: 1.44 · 19.93 ≈ 28. A has height at most 2·log₂(n + 1): 2 · 19.93 ≈ 39. In a red-black tree the longest path is at most twice the shortest; AVL is balanced more tightly, so search is a little faster and insertion and deletion a little more expensive.

Every AVL tree can be coloured as a red-black tree. The converse is false: the tree below is a valid red-black tree (2 black nodes on every path to a NIL), but at the root 10 the left height is 0 and the right height 2: balance factor -2.

5B15B25R40R30B20R10B
A valid red-black tree that is not an AVL tree.

5B-trees and comparison

1810, 20, 30, 40, 50, 60, 70 are inserted in order into an empty B-tree of order 3 (at most 2 keys per node). Show every split and write the final tree.Midterm · trace

When a node reaches 3 keys, its median moves up to the parent and the node splits in two. The tree is written level by level; "/" moves down one level.

InsertedWhat happenedTree
10, 20They fit in the root leaf.[10 20]
30[10 20 30] overflows; 20 moves up, a new root.[20] / [10] [30]
40It fits in the right leaf.[20] / [10] [30 40]
50[30 40 50] overflows; 40 moves up to the root.[20 40] / [10] [30] [50]
60It fits in the right leaf.[20 40] / [10] [30] [50 60]
70[50 60 70] overflows; 60 moves up to the root. The root [20 40 60] overflows; 40 moves up, a new root.[40] / [20] [60] / [10] [30] [50] [70]

In the last insertion the split went up two levels and the tree grew to 3 levels. All leaves are still on the same level. Even with sorted insertion a does not turn into a chain.

19A B-tree of order 5 has height 2 (3 levels). How many keys can it hold at least and at most?Final · concept

At most: every node is full, with 4 keys and 5 children. The levels have 1, 5 and 25 nodes: 31 nodes · 4 = 124 keys. The general formula is m^(h+1) - 1 = 5³ - 1 = 124.

At least: the root has 1 key and 2 children; other nodes have at least ⌈5/2⌉ = 3 children, that is 2 keys. Level 1 has 2 nodes · 2 = 4 keys, level 2 has 6 nodes · 2 = 12 keys. In total 1 + 4 + 12 = 17. The general formula is 2·⌈m/2⌉^h - 1 = 2 · 9 - 1 = 17.

20For the index of a table of 1,000,000 records on disk, would you use a B-tree of order 100 or an AVL tree? What is the height of the B-tree?Final · comparison

On disk every node needs its own read, and a disk read is far slower than a comparison in memory. So you pick the shorter path in nodes: the B-tree.

  • A tree of order 100 with 3 levels holds at most 100³ - 1 = 999,999 keys; 1,000,000 keys do not fit, so at least 4 levels are needed.
  • A tree of height 4 holds at least 2 · 50⁴ - 1 ≈ 12.5 million keys; 1,000,000 keys cannot fill it, so 5 levels are impossible.
  • Result: height 3 (4 levels), so a search reads at most 4 nodes. In an AVL tree the same search reads between 20 and 28 nodes.
21Which structure would you pick in each case: (a) repeatedly taking the highest-priority job while new jobs keep arriving, (b) listing records in order and running range queries in memory, with frequent inserts and deletes, (c) a dictionary built once and searched very often, (d) the index of a large table on disk.Final · comparison

Each structure is good at a different job; in an exam you should also write why you chose it.

  • (a) Heap. Peek is O(1), insert and remove O(log n). No ordered listing is needed, so a balanced tree would do extra work.
  • (b) Red-black tree (or AVL). Inorder traversal gives sorted order; insert and delete are O(log n). A red-black tree rotates less, so it is usually chosen for data that changes often.
  • (c) AVL tree. It is shorter, so search is a little faster; changes are rare, so the cost of rotations does not matter.
  • (d) B-tree (in practice a B+ tree). A node matches one disk block, the tree is very short and few disk reads are made.

6Try it

In a min-heap of distinct values, where can the largest value be?

Show the answer

The answer is B. The largest value cannot have a child, because the child would have to be larger. So it can be in any leaf; it need not be at the last index.

In an AVL deletion, what is done if the left child of the unbalanced node has balance factor 0?

Show the answer

The answer is A. The left side is heavy and the left child is balanced: one right rotation balances the tree. A double rotation is needed only if the left child leans right (-1).

What happens when 10, 20, 30 are inserted into an empty B-tree of order 3?

Show the answer

The answer is B. In a tree of order 3 a node holds at most 2 keys. When 30 arrives the node overflows, and the median 20 moves up and becomes the new root.

Lessons you mark show up in the curriculum. If you are signed in, they are saved to your account too.