CMPS 144 Intersession 2020
Lab #9: Binary Search Trees

               40 
              /  \
             /    \
            /      \
           /        \
          /          \
         /            \
        /              \
       /                \
     20                  58
    /  \                /  \
   /    \              /    \
  /      \            /      \
 /        \          /        \
4          29      47          67
 \        /  \       \        /  \
  10    25    35      52    60    73
 /  \        /       /  \
6    12    32      49    55
 \
  8
The problems in this lab can be answered using pen(cil) and paper. Submit your answers to your instructor. All the problems relate to the binary search tree shown to the right.

1. Show what the tree would look like after doing each of the following operations. (Note: Each operation should be applied to the original tree shown to the right, not to the tree resulting from performing the previous operation(s).)

You need not reproduce the entire tree each time, but you should show enough surrounding context to make it clear which part of the tree was affected by the operation and what changes occurred there.

(a) Insert 6
(b) Insert 33
(c) Insert 44
(d) Remove 25
(e) Remove 4
(f) Remove 40

2. Below are two methods, each of which recursively traverses a binary tree and prints the values stored in the tree's nodes. Notice the difference between their respective else-branches.

(a) Show the output produced by printInOrder() when applied to the tree shown above. Given the order of the statements in the else-branch, it follows that the value in a node is printed after all those in its left subtree and before those in its right subtree.

(b) Show the output produced by printPreOrder() when applied to the tree shown above.

printInOrder()printPreOrder()
public static void printInOrder(BinTree t) {
   if (t.isEmpty()) { }
   else {
      printInOrder(t.leftSubtree());
      System.out.print(t.getRoot() + " ");
      printInOrder(t.rightSubtree());
   }
}
public static void printPreOrder(BinTree t) {
   if (t.isEmpty()) { }
   else {
      System.out.print(t.getRoot() + " ");
      printPreOrder(t.leftSubtree());
      printPreOrder(t.rightSubtree());
   }
}