Introduction to Algorithms, 2021-2
Week 10: Exercises

1. Random Tree

Write a function randomTree(h) that builds a complete binary tree of height h. Every value in the tree should be a random integer in the range 0 .. 999.

2. Complete Tree

Write a function completeTree(h) that builds a complete binary tree of height h. Every node's value should be that node's depth.

3. Mirror Image

Write a function mirror(t) that modifies a binary tree, flipping it from left to right so that it looks like a mirror image of the original tree.

4. Maximum Value

a) Write a function max_in_tree(t) that returns the maximum value in a binary tree.

b) Modify the function to be more efficient if the input tree is known to be a binary search tree.

5. Ancestor Check

Write a function isAncestor(p, q) that takes pointers to two nodes p and q in a binary tree and returns true if p is an ancestor of q.

6. Tree Experiment

Write a function that takes an integer N and inserts N random values in the range from 0 .. N – 1 into a binary search tree. Let r be the ratio of the tree's height to the minimum possible height of any tree that holds N values. The function should compute and return r.

7. Recursive Tree

Write a class TreeSet that implements a set of values using a binary search tree, with methods add() and contains(). Implement these methods using recursion, with no loops. Hint: write recursive helper functions outside your TreeSet class that work with Node objects.

8. Most Common Word

Write a program that reads a text file and prints the most common word in the file, along with its count of occurrences. Assume that words are sequences of Latin letters (A .. Z, a .. z), and ignore case. Do not use a Python dictionary. Instead, use a binary search tree to store the word counts.

9. Tree Range

Write a method that determines how many values v in a binary search tree of unique integers fall in the range a ≤ v ≤ b, where a and b are function parameters. The function should run in time O(h + n), where h is the tree height and n is the number of integers in the range.

10. Biggest Gap

Write a function that returns the greatest difference between any two consecutive values in a binary search tree.

11. Tree Successor

Write a method which, given a binary search tree of non-negative integers and an integer i, returns the next highest value in the tree, i.e. the smallest value in the tree that is greater than i. Return -1 if there are no values greater than i. Assume that all integers in the tree are unique. The value i may or may not be present in the tree. Your function should run in time O(h), where h is the height of the tree.