CPSC 331 — Solution for Question #1 on Practice Examination This question concerned the following binary search tree T . 6 3 10 1 8 12 (a) You were first asked to describe a method to insert a value into a binary search tree. Then you were asked to draw the tree that would produced by inserting 7 into the above tree T , Method To Insert a Value: If the tree is empty then create a new node that stores the input value, and make this the root of the tree. Otherwise compare the input value to the value stored at the root of this tree. • If the input value is less than the value at the root, recursively insert the input value into the left subtree of the root. • If the input value is greater than the value at the root, recursively insert the input value into the right subtree of the root. • Finally, if the input value is equal to the value at the root, throw an exception and do not change the tree at all. Tree Obtained by Inserting 7 into T : 6 3 10 1 8 7 1 12 (b) You were next asked to suppose that you wish to delete a value that is stored at a node with two children, and to describe how this should be done. You were then asked to draw the binary search tree that would be produced after deleting 6 from the binary search tree T shown at the beginning of this question. How To Delete a Value at a Node with Two Children: Let x be the node where the value to be deleted is located. Find the node y storing the smallest value in the right subtree of x by starting with the right child of x, and repeatedly moving down from a node to its left child until a node, y, with no left child has been found. The value at y can now be written into x (replacing the value to be deleted) and the right child of y can be promoted to replace y in the tree. (This will be a null node if y was a leaf.) Tree Obtained by Deleting 6 from T : 8 3 10 1 12 Note: It is also acceptable to overwrite the value at the node you start from with the largest value in the left subtree of this node, instead. In this case, the binary search tree obtained by deleting 6 would be as follows. 3 1 10 8 2 12