A document from MCS 275 Spring 2024, instructor Emily Dumas. You can also get the notebook file.

MCS 275 Spring 2024 Worksheet 7

  • Course instructor: Emily Dumas

Topics

The main topics of this worksheet are:

  • Trees
  • Binary search trees

Project 3 will focus on tree-like data structures, so it is very important to get practice with this material!

Resources

These things might be helpful while working on the problems. Remember that for worksheets, we don't strictly limit what resources you can consult, so these are only suggestions.

1. Node relationship

Suppose you have two Node objects (or objects of a subclass of Node) as defined in trees.py. Let's call them x and y. You might ask how they are related to one another, if it all. In general, exactly one of the following statements will be true:

  1. The nodes do not lie in the same tree
  2. The nodes are equal
  3. One of the nodes is an ancestor of the other
  4. The nodes lie in the same tree, but neither is an ancestor of the other

Write a function node_relationship(x,y) that takes two nodes and returns one of these strings:

  1. "unrelated"
  2. "equal"
  3. "ancestor"
  4. "cousin"

according to which of the cases listed above describes the relationship between x and y.

(Note that the use of "cousin" to describe case (3) doesn't fit the genealogical analogy perfectly, as it would also include the case of siblings.)

Also, make test cases for your function that generate each of the possible answers.

Get ready to edit trees.py

The rest of the worksheet focuses on adding features to the module trees.py from lecture. To prepare for that, download these files and save them in a directory where you'll work on worksheet 8.

Know how to test your code

It will be hard to test your code if you don't have any search trees to test it with. To that end, I created a module treeutil.py (which you were asked to download above) that will generate random binary search trees on request. It can also give a random node of the tree, or a random pair of nodes.

Open the full documentation of the module in a separate browser tab, and keep it open as you work:

The main things you'll be doing in such tests are:

  • Using treeutil functions to make trees to test your code on
  • Using treevis.treeprint to display trees for manual inspection

2. Minimum and maximum

Add two new methods, minimum and maximum to the BST class for finding the node with the smallest or largest key in the subtree that has this node as its root. Use these function definition lines and docstrings:

In [ ]:
    # These should go inside class `BST` in `trees.py`
    def minimum(self):
        """
        In the subtree that this node is the root of, find and
        return the the smallest key.
        """
        
    def maximum(self):
        """
        In the subtree that this node is the root of, find and
        return the the largest key.
        """

3. Depth

Add a method depth to the BST class that computes the depth of the tree. (That is, when you call A.depth() on a node A, you get the maximum number of descending edges that you can follow in the tree that has A as its root).

Note that both an empty BST and a 1-node BST are considered to have depth zero by this convention.

Use these function definition lines and docstrings:

In [ ]:
    # This should go inside class `BST` in `trees.py`
    def depth(self):
        """
        Return the length (in number of edges) of the longest descending
        path starting from this node.
        """

4. Interval of a node

Suppose you are given a binary search tree T and a node x that has no children. If you change the key of x, the tree may or may not be a binary search tree.

Here's an example to illustrate this. Consider this BST:

       [15]

   [9]      [29]

[5]  [12]

If x is the node with key 12, then changing the key to 13 still gives a binary search tree:

       [15]

   [9]      [29]

[5]  [13]

But if we change the key to 6, the result is not a binary search tree; the right subtree of the node with key 9 contains keys smaller than 9:

❌THIS IS NOT A BST❌
       [15]

   [9]      [29]

[5]  [6]

And if we change the key to 18, the result is not a binary search tree. The left subtree of the root node contains a node with key larger than 15:

❌THIS IS NOT A BST❌
       [15]

   [9]      [29]

[5]  [18]

Now, if you look more closely at this example, you can convince yourself that the key 12 can be changed to any number in the closed interval $[9,15]$ while keeping the BST condition, but that anything outside of this range will result in a non-BST. This is called the interval of the node.

Add a method to BST that can be called whenever the node has no children, and which returns a tuple (kmin,kmax) where kmin and kmax are the smallest and largest values (respectively) that the key of that node could be changed to while keeping the BST condition. In some cases, there may be no lower or upper limit, in which case the value None should be returned for kmin, kmax, or both. If called on a node that has children, it should raise an exception.

Use this method definition:

In [ ]:
    # This should go inside class `BST` in `trees.py`
    def interval(self):
        """
        If this node has no children, return the minimum and maximum key values that
        could be given to this node without violating the BST condition.  The value None
        is used to indicate that the range of allowable values has no upper or lower
        bound.

        If the given node has children, raises ValueError.
        """

Challenge

If you have extra time and do not have questions about project 2, try these:

  • Write an iterative version of BST.search, i.e. one that never recursively calls the search method of that node of any other node.

  • Write an iterative version of BST.insert, i.e. one that never recursively calls the insert method of that node of any other node.

Revision history

  • 2024-02-18 Initial publication