CMPS 144 Spring 2022
May 5 Quiz Sample Solutions

A Binary Search Tree
               39 
              /  \
             /    \
            /      \
           /        \
          /          \
         /            \
        /              \
       /                \
     18                  56
    /  \                /  \
   /    \              /    \
  /      \            /      \
 /        \          /        \
5          30      47          70
 \        /  \       \        /  \
  10    22    35      52    64    73
 /  \     \          /  \
7    15    25      50    54
    /        \
  12          28
    \
     13
With respect to the binary search tree shown to the right, show what it 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). Which is to say that you should show six distinct trees.)

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.

1. Insert 16
Solution: A new leaf node containing 16 becomes the right child of the 15-node.

2. Insert 72.
Solution: A new leaf node containing 72 becomes the left child of the 73-node.

3. Delete 28.
Solution: The leaf node containing 28 disappears.

4. Delete 5.
Solution: As the node containing 5 has a child, we cannot simply make it disappear without also taking measures to ensure that its proper descendant nodes remain in the tree. Because the 5-node has only one child, we connect its child node directly to 5's parent. That is, the 10-node (5's lone child) becomes the left child of the 18-node.

5. Delete 56.
Solution: As the 56-node has two children, we place into that node the smallest key in its right subtree (64) and remove that key from that subtree. Here, that means that the 56-node becomes the 64-node and the original 64-node, which is a leaf, disappears.

An alternative is to replace 56 by the largest key in its left subtree, which is 54. In that case, the 54-node (a leaf) disappears.

6. Delete 18.
Solution: As the 18-node has two children, we place into that node the smallest key in its right subtree (22) and remove that key from that subtree. Here, that means that 22 replaces 18 in the 18-node. Because the original 22-node has one child, to remove 22 entails connecting its child directly to its parent, here meaning that the 25-node becomes the left child of the 30-node.

An alternative would be to replace 18 in the 18-node by the largest key in its left subtree, which is 15. In that case, 15 is removed from that left subtree by making the 12-node the right child of the 10-node.