Problem Set

Version: 0.6.22

Problem Set#

Objectives:

Practice the concepts introduced in the Trees module

This problem set is optional practice. Work on it wherever you like, alone or in groups, and with any resources you find useful. Unless a problem says otherwise, answer with pen and paper or in pseudocode; implementation tasks can be done in any programming language.

Problems are roughly ordered by difficulty, from ★ (warm-up) to ★★★★ (challenging). The last two problems introduce topics that are not covered in the lectures: Each one starts with a short background that gives you everything you need.

Every problem comes with a solution, hidden in a dropdown below it. Give the problem a real try before you open it: Most of the learning happens while you are stuck.

Core Problems#

Exercise 1 (Counting on Recursion ★)

Recall from Lecture 5.1 that a tree \(t = (r, c)\) is made of a root \(r\) and a sequence \(c\) of disjoint children trees. Assume every node gives access to node.children, the (possibly empty) sequence of its children, as in the “sequence of children” representation. Consider the tree shown on Fig. 2.

../_images/counting.svg

Fig. 2 A general tree with nine nodes#

  1. Write recursive procedures for the following three operations:

    • size(node) returns the number of nodes in the subtree rooted at node;

    • height(node) returns the height of the subtree rooted at node, where a single node has height 0;

    • leaves(node) returns the number of leaves in the subtree rooted at node.

  2. Run height(R) on the tree above. List the calls in the order they return, together with the value each of them returns.

  3. Look at the order you obtained in the previous question. Which traversal is it? Explain why all three operations end up visiting the nodes in this order.

  4. How many calls to size does size(R) trigger in total, for a tree with \(n\) nodes? What is the time complexity of size? Justify your answer.

Exercise 2 (One Tree, Two Encodings ★)

Lecture 5.1 shows a second way to store a general tree: Every node keeps only two references, one to its left-most child and one to its next sibling (see Fig. 1.25). If we read the first reference as a “left” child and the second as a “right” child, any general tree becomes a binary tree, where every node has at most two children.

Consider for instance the tree shown on Fig. 3. Node A has three children, so it is not a binary tree. In its encoding, shown on Fig. 4, A keeps a link to its first child B only. B links to its next sibling C, which in turn links to its own first child E and to its next sibling D.

../_images/encodings-example-tree.svg

Fig. 3 A general tree, where Node A has three children#

../_images/encodings-example-binary.svg

Fig. 4 Its encoding as a binary tree. Solid arrows lead to the left-most child, dashed arrows to the next sibling.#

The tree from Fig. 2 is not a binary tree either: Its root has four children.

  1. Draw the binary tree that encodes the tree from Fig. 2. What is its height? Compare it with the height of the original tree.

  2. List the nodes of both trees in pre-order. Then list the nodes of the general tree in post-order, and the nodes of the binary tree in in-order (left subtree, then the node itself, then the right subtree). What do you notice?

  3. Explain why the post-order of a general tree always matches the in-order of its encoding.

    Hint: Given a node \(v\), which nodes of the general tree end up in the left subtree of \(v\) in the encoding? Which end up in its right subtree?

  4. A classmate reuses the size procedure for binary trees, where an empty tree has size 0:

    size(node):
       if node is null:
          return 0
       return 1 + size(node.left) + size(node.right)
    

    They call it on Node S of the encoding. Does the result match the size of the subtree rooted at S in the general tree? Explain why size(R) still returns the correct answer, then fix the procedure so that it returns the size of the general subtree for any node.

Exercise 3 (Rebuilding from Traversals ★★)

A traversal turns a tree into a sequence. Can we go the other way, and rebuild a binary tree from its traversals? In this problem, all nodes carry different labels. Recall that the in-order visits the left subtree, then the node itself, then the right subtree (see Exercise 2).

  1. A binary tree with nine nodes gives the following two sequences:

    • Pre-order: M, K, Q, A, J, P, T, R, L

    • In-order: Q, K, J, A, M, P, R, T, L

    Rebuild the tree. Explain how you find the root, and how you decide which nodes belong to its left and right subtrees.

  2. Turn your method into a recursive procedure rebuild(preorder, inorder) that returns the root of the tree. What is its time complexity in the worst case? Which tree shape triggers this worst case?

  3. Does the pre-order alone determine the tree? How many different binary trees have the pre-order A, B, C? Draw them all.

  4. Do the pre-order and the post-order together determine the tree? If not, find two different binary trees that share both sequences. Can you think of a family of binary trees for which these two sequences are enough?

Exercise 4 (The Lazy Validator ★★)

Recall from Lecture 5.2 the invariant of a binary search tree: Every node carries an item that is greater than or equal to all the items in its left subtree, and strictly smaller than all the items in its right subtree. A classmate wants to check whether a binary tree satisfies this invariant, and writes the following procedure:

isBST(node):
   if node is null:
      return true
   if node.left is not null and node.left.item > node.item:
      return false
   if node.right is not null and node.right.item <= node.item:
      return false
   return isBST(node.left) and isBST(node.right)

Their argument: “It checks every node against its children, and it does so for every node in the tree, so it must be correct.”

../_images/validator.svg

Fig. 8 A binary tree with eight nodes#

  1. Run isBST on the tree shown on Fig. 8. What does it return? Is this tree a BST? Search for 30 in this tree, as the lecture’s contains operation would do. What happens?

  2. What is the smallest tree (with the fewest nodes) that isBST accepts, although it is not a BST? Explain why no smaller tree can fool it.

  3. Fix the procedure.

    Hint: As you walk down the tree, every node you pass narrows the range of items allowed below it. Write a procedure isBST(node, low, high) that also checks that every item in the subtree lies within this range. How do you call it on the root? What is its time complexity?

  4. Another classmate suggests a different approach: Run an in-order traversal, and check that the resulting sequence never decreases. Does that work with the invariant above? If not, give a counterexample, and say under which condition the approach does work.

    Hint: Think about duplicates.

Exercise 5 (Inner Trouble ★★)

Lecture 5.4 distinguishes two ways in which an AVL tree can become unbalanced: The outer cases, fixed by a single rotation, and the inner cases, which need two. This problem focuses on the inner cases, and on what happens when we delete.

We use the conventions of the lecture: The empty tree has height \(-1\), the balance factor of a node is \(b = h(L) - h(R)\), and a left rotation lifts up the right child. Insertions proceed as in a plain BST before rebalancing, and a deleted node that has two children is replaced by its predecessor.

  1. Starting from an empty AVL tree, insert the keys 50, 20, 70, 10, 30, and 25, in this order. Draw the tree after every insertion, and write down the balance factor of every node. When the tree becomes unbalanced, say which node is unbalanced, which of the four cases applies (outer or inner, left or right), and which rotations restore the balance. Draw the tree after each rotation.

  2. Insert 60 into the resulting tree, and restore the balance. Compare the height of the subtree you rebalanced before the insertion with its height after the rebalancing. Why does this mean that, after an insertion, no node higher up ever needs rebalancing?

  3. Now delete the keys 10, 25, and 20, in this order. Which deletion breaks the balance? What is then the balance factor of the heavy child? Which of the four cases from the lecture applies? Which rotation(s) restore the balance? Check that your final tree is a valid AVL tree.

  4. Explain why the situation from the previous question, where the heavy child has a balance factor of 0, never occurs right after an insertion.

Exercise 6 (Heapify, Step by Step ★★)

We use the minimum binary heap from Lecture 5.3, stored in an array whose first index is 0: The children of the node at index \(i\) sit at indices \(2i+1\) and \(2i+2\).

  1. Heapify the array (14, 9, 17, 3, 12, 5, 8, 1, 6, 10). For every non-leaf node you process, list the swaps you make and give the array afterwards. How many swaps do you make in total? Draw the resulting heap as a tree.

  2. Now build a heap by inserting the same items, in the same order, into an empty heap. Give the array after every insertion, and count the swaps. Do you obtain the same heap? Which method made fewer swaps?

  3. Consider the keys 1 to 7. In which order should you insert them into an empty heap to make as many swaps as possible? How many swaps is that? How many swaps does heapify make on an array that holds the keys in that same order?

    Explain the difference. Hint: In a complete binary tree, about half the nodes are leaves. How far can a leaf move during an insertion? During heapify?

  4. A game server receives \(n\) scores, one at a time, and must report the \(k\) highest ones at the end. Memory is short: You may only use a minimum heap that never holds more than \(k\) scores.

    Design a procedure that solves this problem, and run it on the scores (42, 17, 63, 8, 55, 71, 23, 60, 90, 12) with \(k = 3\). Give the heap array after every score. What is the time complexity of your procedure, in terms of \(n\) and \(k\)? Why does a minimum heap fit better here than a maximum heap?

Exercise 7 (Counting Disk Reads ★★)

Lecture 5.5 introduces B-trees to reduce the number of disk accesses. We use its conventions with \(k = 4\): Only the leaves carry entries, at most four each. An internal node has at most four children, separated by up to three keys, and every key is the smallest key found in the subtree on its right. Every node except the root holds at least \(\lfloor k/2 \rfloor = 2\) entries or children. Consider the B-tree shown on Fig. 14.

../_images/btree-disk.svg

Fig. 14 A B-tree with \(k = 4\), holding ten entries#

To leave no room for doubt, we fix the following rules:

  • An overflowing node (five entries or children) keeps the first three, and moves the last two into a new node, placed just on its right. Its parent gets a new key: The smallest key under the new node.

  • To repair an underflowing node, first look at its left sibling: If it holds more than two entries (or children), borrow its last one. Otherwise, look at its right sibling, and borrow its first one under the same condition. Otherwise, merge with the left sibling if there is one, or else with the right sibling. In every case, update the keys of the parent.

We count disk accesses as in the disk-access model. Each node fills exactly one block: Reading a node costs one READ_BLOCK, and writing it costs one WRITE_BLOCK. Memory is small, so every operation starts by reading the root, but a node read during an operation stays in memory until the operation ends. Every node that is created or changed is written exactly once, at the end of the operation. Discarding a node costs nothing, and so does keeping track of where the root is.

  1. Insert the key 28. Draw the tree after every split. Which nodes do you read, and which do you write? How many disk accesses does the insertion cost in total?

  2. Starting from the tree you obtained, delete the keys 30, 10, and 50, in this order. Draw the tree after each deletion, say how you repair every underflow (borrowing or merging, and with which sibling), and count the reads and writes.

    After the last deletion, the root is left with a single child. Does this break the B-tree rule? What would you do about it, and why does it matter for later operations?

  3. Consider a B-tree of height \(h\), where, as for any tree, a single node has height 0. In the worst case, how many disk accesses does an insertion cost? Which insertion triggers this worst case? Show that a deletion also costs \(O(h)\) disk accesses.

  4. A database stores \(10^9\) entries in a B-tree, on a hard drive whose blocks hold 4096 bytes. A key and the address of a block take 8 bytes each, so we choose \(k = 4096 / 16 = 256\). What are the smallest and the largest possible heights of this B-tree? How many blocks does a search read at most?

    Compare with a perfectly balanced BST holding the same entries, where every node sits in its own block. Assuming a disk access takes 10 ms, how long does a search take in each case?

    Hint: The tree is tallest when its nodes are as empty as the rule allows. At least how many entries does a B-tree of height \(h\) hold?

Exercise 8 (Prefix Power ★★)

Lecture 5.6 stores a set of words in a prefix tree: The root carries the empty symbol \(\varepsilon\), every other node carries one symbol, and a leaf \(\bot\) marks the end of each word. The lecture explains how to check whether a word is in the tree, but leaves prefix search, insertion, and deletion open. This problem fills these gaps. Consider the set of eight words

\[S = \{ \mathit{in},\, \mathit{inner},\, \mathit{tea},\, \mathit{tear},\, \mathit{ten},\, \mathit{tend},\, \mathit{to},\, \mathit{toe} \}\]
  1. Draw the prefix tree that holds \(S\). How many nodes does it have? Compare with the total number of symbols in the eight words. Explain why the leaves \(\bot\) are necessary in this tree.

  2. In a compressed prefix tree, every chain of nodes that have a single child is merged into a single node, which carries all their symbols. Afterwards, every node except the leaves has at least two children. Draw the compressed version of your tree. How many nodes are left?

    Explain how to check whether the compressed tree contains a word, and run your method on “te”, “tend”, and “inn”.

  3. Design a procedure prefixSearch(root, p) that returns all the words of a (non-compressed) prefix tree that start with the prefix \(p\). Run it on the prefixes “te”, “in”, “tex”, and on the empty prefix. What is its time complexity?

    What changes in a compressed tree? Think in particular of the prefix “inn”.

  4. Add the word “i” to your compressed tree, then remove the word “in”. Draw the tree after each step. In general, when does an insertion force you to split a node? When does a deletion force you to merge nodes?

Exercise 9 (One Pass Is Enough ★★★)

Many questions about a binary tree combine answers computed on its subtrees. Computed carelessly, the same answers get recomputed over and over. This problem shows how to compute everything in a single traversal.

As in Lecture 5.4, the empty tree has height \(-1\), and we say a binary tree is balanced when the balance factor of every node lies in \([-1, 1]\). We ignore the items: The tree need not be a BST. The diameter of a tree is the number of edges on the longest path between two of its nodes. Such a path climbs up from one node and goes down to the other, and it need not pass through the root.

../_images/one-pass.svg

Fig. 22 A binary tree with ten nodes#

  1. A classmate checks the balance as follows, where height returns the height of a subtree, as in Exercise 1:

    isBalanced(node):
       if node is null:
          return true
       if abs(height(node.left) - height(node.right)) > 1:
          return false
       return isBalanced(node.left) and isBalanced(node.right)
    

    Which nodes of the tree shown on Fig. 22 are unbalanced? Which one makes isBalanced return false?

    Now run isBalanced on a perfect binary tree of height \(h\), whose leaves all sit at depth \(h\). How many times do the calls to height visit a node at depth \(d\)? Deduce the time complexity of isBalanced on such a tree, in terms of its number of nodes \(n\).

  2. Write a procedure that checks the balance in a single traversal, visiting every node at most once. What is its time complexity? Run it on Fig. 22. Which node reveals the imbalance first? Which nodes are never visited?

    Hint: A node needs the heights of its children to check its own balance, and to compute its own height. Let a single procedure return both, and agree on a special value meaning “unbalanced”.

  3. What is the diameter of the tree on Fig. 22? Give a longest path. Does it pass through the root?

    The classmate now writes:

    diameter(node):
       if node is null:
          return 0
       through = height(node.left) + height(node.right) + 2
       return max(through, diameter(node.left), diameter(node.right))
    

    Explain why it is correct. What is its time complexity on a tree where every node has a single child? Write a procedure that computes the diameter in a single traversal.

  4. Adapt your single-pass procedure to the general trees of Exercise 1, where a node may have any number of children. Run it on the tree shown on Fig. 2: What is its diameter, and which two nodes are the furthest apart?

    Hint: A longest path has a single highest node. Through which of its children can it go?

Going Further#

These problems go beyond the lectures: Huffman coding and scapegoat trees are not part of the syllabus. Both build directly on this module, though. Huffman codes are binary prefix trees, and scapegoat trees are another way to keep a search tree balanced. Each problem starts with a short background that introduces everything you need.

Exercise 10 (Squeezing BANANA BANDANA ★★★)

Background. A computer stores text as a sequence of bits, so every symbol needs a code: A sequence of bits that stands for it. The simplest choice gives every symbol a code of the same length. With five symbols, three bits each are enough, for example A = 000, B = 001, and so on. But some symbols are much more frequent than others. If we give them shorter codes, and give longer codes to the rare ones, the whole text takes fewer bits.

Codes of different lengths raise a problem, though: Where does one code end and the next begin? A code is prefix-free when no code is the beginning (the prefix) of another one. With a prefix-free code, we can read the bits from left to right, and as soon as the bits read so far form a code, we know which symbol it stands for.

A prefix-free code is a binary tree. Every symbol sits in a leaf, and its code describes the path from the root to that leaf: 0 means “go to the left child” and 1 means “go to the right child”. This is the prefix tree of Lecture 5.6, over the alphabet \(\{0, 1\}\). Because no code is the prefix of another, every code ends in a leaf, and we need no \(\bot\) marker. To decode, we start at the root and follow the bits. Whenever we reach a leaf, we output its symbol and jump back to the root.

Huffman’s algorithm builds the best such tree for a given text. It uses a minimum priority queue, as in Lecture 5.3, whose items are trees and whose priorities are weights:

  1. Count how often each symbol occurs. For each symbol, enqueue a tree made of a single leaf, whose weight is that count.

  2. While the queue holds more than one tree, dequeue the two lightest trees, join them as the left and right children of a new root, and enqueue the result, whose weight is the sum of their weights.

  3. The last tree left in the queue is the code tree.

The algorithm leaves ties open: When several trees have the same weight, any choice is allowed.

Problem. We want to store the text “BANANA BANDANA”, where the space “ “ counts as a symbol, written ␣. Consider the following three codes:

Symbol

A

N

B

D

␣

Code 1

0

1

01

10

11

Code 2

00

01

10

110

111

Code 3

000

001

010

011

100

  1. Which of these codes are prefix-free? For Code 1, find a sequence of bits that can be decoded in two different ways. Draw the trees of the other two codes, and use the tree of Code 2 to decode 110000100.

  2. How many bits does the text take with Code 2? With Code 3?

  3. Run Huffman’s algorithm on the text. Give the content of the priority queue after every step, draw the resulting tree, and give the code of every symbol. How many bits does the text take now? Does a different way of breaking the ties change this number?

  4. Show that in a best code tree (one that minimises the total number of bits), every internal node has exactly two children.

    Then show that there is always a best tree where the two least frequent symbols are siblings, at the deepest level. This is the key step in proving that Huffman’s algorithm is optimal.

    Hint: What happens to the total number of bits if you swap a frequent symbol with a rarer one that sits deeper in the tree?

  5. A text uses \(m\) different symbols. What is the time complexity of Huffman’s algorithm, once the symbols are counted, if the priority queue is a binary heap? Find a text with four different symbols where the Huffman code saves nothing compared with a code where every symbol takes two bits.

Exercise 11 (Scapegoat Trees ★★★★)

Background. AVL trees stay balanced by storing extra information in every node, and by fixing the tree with rotations after every insertion and deletion. Scapegoat trees take a lazier approach: Nodes store nothing but their item and their two children, and the tree is a plain BST most of the time. Only when a new node lands too deep do we pick one subtree, the scapegoat, and rebuild it from scratch.

We fix a parameter \(\alpha\) with \(1/2 < \alpha < 1\). In this problem, \(\alpha = 2/3\). The size of a node is the number of nodes in its subtree, as in Exercise 1, and the root has depth 0. A node \(w\) is weight-balanced when each of its children has a size of at most \(\alpha \cdot \mathrm{size}(w)\): Neither side holds much more than its share of the nodes.

A scapegoat tree with \(n\) nodes handles an insertion as follows:

  1. Insert the new node \(x\) as in a plain BST (see Lecture 5.2).

  2. If the depth of \(x\) is at most \(\log_{1/\alpha} n\), where \(n\) now counts \(x\), stop here.

  3. Otherwise, walk up from \(x\) towards the root, and stop at the first ancestor \(w\) that is not weight-balanced. This node is the scapegoat.

  4. Rebuild the subtree rooted at \(w\) into a perfectly balanced tree: List its \(m\) items in order (with an in-order traversal), make the item at position \(\lceil m/2 \rceil\) the new root, and build its left and right subtrees the same way, from the items on each side.

Problem.

  1. Starting from an empty scapegoat tree, insert the keys 10, 20, 30, 40, 50, 60, and 70, in this order. Draw the tree after every insertion. Whenever the new node lands too deep, give the size of every ancestor you check on the way up, say which node is the scapegoat, and draw the tree after the rebuild.

    Compare the final height with that of a plain BST built from the same insertions.

  2. Show that, whenever the new node \(x\) lands too deep, the walk up always finds a scapegoat.

    Hint: Assume that every ancestor of \(x\) is weight-balanced. Going down one step from the root, how much can the size shrink at most? What does this give for the size of \(x\)?

    One can show that the rebuild always brings \(x\) back within the bound. What is then the largest possible height of a scapegoat tree with \(n\) nodes, built by insertions only? Compare it with the bound \(1.44 \log_2 n\) of AVL trees.

  3. How long does it take to rebuild a subtree with \(m\) nodes? Find a sequence of insertions where a single insertion triggers a rebuild of \(\Theta(n)\) nodes.

    Since the nodes do not store their size, the walk up must compute it. Show that finding the scapegoat takes \(O(\mathrm{size}(w))\) time, so it costs no more than the rebuild itself.

    Hint: When you step up from a child \(u\) to its parent, you already know the size of \(u\). Which subtree do you still need to count?

  4. Rebuilding is expensive, but it should not happen often. Right after a rebuild, the scapegoat \(w\) has \(m\) nodes in its subtree and is perfectly balanced. Show that at least \(\Omega(m)\) insertions into the subtree of \(w\) must happen before \(w\) can be a scapegoat again.

    Deduce that \(n\) insertions into an empty scapegoat tree take \(O(n \log n)\) time in total, so that each insertion costs \(O(\log n)\) on average.

    Hint: Pay for each rebuild with the insertions that made it necessary. Under how many scapegoats can a single inserted node sit?