CMPS 144L: Lab Activity on Binary Search Trees

A Binary Search Tree
                   40 
                  /  \
                 /    \
                /      \
               /        \
              /          \
             /            \
            /              \
           /                \
          /                  \
         /                    \
        /                      \
       /                        \
     20                         58
    /  \                       /  \
   /    \                     /    \
  /      \                   /      \
 /        \                 /        \
4          29             50          67
 \        /  \           /  \        /  \
  10    25    35       42    52    60    73
 /  \        /           \     \
6    12    32            47    55
 \         /            /  \
  8       30          44    48
The problems associated to this activity are intended to be answered using pen/pencil and paper or a plain text file. 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 53
(b) Remove 25
(c) Remove 4
(d) 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.

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

(a) Show the output produced by printInOrder() when applied to the tree shown above. Notice that the print statement lies between the two recursive calls in the method's else-branch. Consider the consequence of that with respect to when each node's value is printed relative to when the values in its left and right subtrees are printed.

(b) Show the output produced by printPreOrder() when applied to the tree shown above. Notice that the print statement precedes the two recursive calls in the method's else-branch. Consider the consequence of that with respect to when each node's value is printed relative to when the values in its left and right subtrees are printed.