Homework 4: Binary Search Trees (due 2/25/2015)
For your fourth homework, you will be adding some functionality to the binary search tree class located here: BinarySearchTree.java. You will need to add 3 methods to this class (plus any helper methods that you need). The methods that you need to add are:
T ElementAt(int index)
Returns the ith largest element in the binary search tree. So, ElementAt(0) would return the smallest element in the tree, ElementAt(1) would return the second smallest element in the tree, and so forth. This method does not need to be efficient it only needs to compute the correct value.int NumLarger(T elem)
Returns the number of elements in the tree greater than elem. Be sure to make your code as efficient as possible -- only examine the sections of the tree that you need to in order to compute the desired information.void Balance()
Reorders the tree so that it is balanced -- that is, so the height is as small as possible. The easiest way to rebalance the tree is to:- Create an array that contains all of the elements in the tree in order (which you can do by using a modified version of print that "prints" to an array)
- Create a new tree, by inserting all of the elements from the array into the tree. In order to make the tree balanced, you are likely going to want to write a recursive method to do the insertions:
- First insert the element in the middle of the array.
- Then recursively insert the rest of the elements in the array (you will likely want to make two recursive calls here)
What's with all this T nonsense?
Note that the type for elements is T. What is T? That is a generic type in Java. You are not saying what the type T is -- it could be anything, an integer, a string -- anything that implemenets the Comparable interface. When you instantiate a BinarySearchTree, then you tell the compiler what type T actually is. That way, the compiler will do more type checking for you, and you won't need to do type casting. For the code you are writing, you don't particularly care what the element type of the BST actually is, so you shoudn't need to deal with 'T' very much. If you have any questions, come by my office!
Submission
Please place BinarySearchTree.java into subversion under:https://www.cs.usfca.edu/svn/<username>/cs245/Homework4/