CS 216 - Data Structures Homework #6

Due: Wednesday 3/20 at the beginning of class.

NOTE: This work is to be done in pairs.

## Binary Search Trees

In these exercises, you will add to the Binary Search Tree implementation we developed together in class. Although you may discuss your algorithms for these problems, your actual implementation must be completed independently.

1. Range: Implement a method public ArrayList<E> getRange(E min, E max) that, given a minimum value min and a maximum value max, returns a sorted list of all (possibly repeated) values in the binary search tree in the range [min, max]. You may assume that min <= max. Your implementation should traverse a minimal subtree as you build the list.

Write stochastic test code that adds n random values from 0 to m-1 to an empty BinarySearchTree<Integer>, prints the tree, calls getRange on a random range of these values, and prints the returned list. Choose values of m and n (e.g. 10 and 20) such that you're likely to have both missing and repeated values.

2. Iterable: Augment your BinarySearchTree<E> so that it now implements Iterable<E>. This implies that you will also implement an Iterator<E> class. This Iterator<E> should be strictly implemented (including exceptions) and should have a functional remove method. Read the Java documentation thoroughly. A correct implementation will allow you to use the enhanced for-loop (a.k.a. "for-each" loop) with your binary search tree.

Hint: Add an inner class BSTIterator implements Iterator<E> that will have full access to the tree's fields. This inner class would benefit from having fields:

• Node<E> current - the current node whose value was just returned by next() (or null if there has been no call to next()) and may be deleted by remove()
• Node<E> next - the successor node to the current node or null if there is no successor
• boolean canRemove - true if and only if there has been no call to remove() since a successful call to next()
remove() can be implemented using your node deletion method, but take care to update current if necessary.

For your stochastic test code, generate a random tree as in the first exercise, print it using our toString() method, and print the values using a for-each loop. Then get an Iterator<E> from the tree and, using all three Iterator methods, remove either all odd values or all even values and print the values again using a for-each loop.