Lab: Binary Search Trees
Objective
In this lab you will deepen your understanding of binary search trees
and practice using the BinaryTree component and recursion by writing
and testing the isInTree static, generic method for BinaryTree<T>.
Setup
To get started, import the project for this lab,
BinarySearchTreeMethods, from the BinarySearchTreeMethods.zip file
available at this link. If you don't
remember how to do this, see the Setup
instructions
in an earlier lab.
Method
-
Take a look at the provided code skeleton of
BinarySearchTreeMethods.javain thesrcfolder and make sure you understand it. You will notice that the main program makes use of a custom utility class,BinaryTreeUtility, that provides a useful static method,insertInTree, used to insert a label in a binary search tree. Here is the documentation:/** * Inserts {@code x} in {@code t}. * * @param <T> * type of {@code BinaryTree} labels * @param t * the {@code BinaryTree} to be searched * @param x * the label to be inserted * @aliases reference {@code x} * @updates t * @requires IS_BST(t) and x is not in labels(t) * @ensures IS_BST(t) and labels(t) = labels(#t) union {x} */ public static <T extends Comparable<T>> void insertInTree(BinaryTree<T> t, T x) {...} -
Complete the body of the
isInTreestatic, generic method by pasting the code you wrote for the homework. Make sure your implementation takes advantage of the fact that the given tree is a binary search tree. -
Run the main program to interactively test your implementation of
isInTree. -
When you think it is working, edit the
BinarySearchTreeMethodsTest.javaJUnit test fixture in thetestfolder and add appropriate test cases for theisInTreemethod. One sample test case is provided as an example of how to set up a binary search tree. -
Run your JUnit test fixture and fix any problems with your implementation of
isInTreeuntil it passes all its test cases and you are confident it is correct (and implemented efficiently). -
If you have extra time, spend it working on the Additional Activities below because they are part of your next project.
Additional Activities
- Fill in the body of the
removeSmallestmethod in theBinarySearchTreeMethods.javafile. - Uncomment the last section of the main program so that it calls
removeSmallestand outputs the labels in the tree smallest-to-largest. Run the main program to test your implementation ofremoveSmallest. - Add appropriate test cases to
BinarySearchTreeMethodsTest.javato test your implementation ofremoveSmallest. Run the JUnit test fixture on your implementation and fix any remaining problems.