CS 216 - Data Structures
Homework #6 |
NOTE: This work is to be done in pairs.
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:
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.