Binary Search Trees
For your second 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:
Comparable ElementAt(int index)
Returns the ith largest elementin 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 NumLess(Comparable elem)
Returns the number of elements in the tree less 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)
The file
BinarySearchTree.java
already has "stubs" for ElementAt, NumGreater, and Balance
-- you just need to fill them in so that they do the correct
thing. (Note -- you will
probably also need to write some helper functions!).
Submission
Please place BinarySearchTree.java into subversion under:
https://www.cs.usfca.edu/svn/$<$username$>$/cs245/Homework2/}
Also, turn in a printout of only the methods you
added or
modified
(not the entire file BinarySearchTree.java). To make your TA's
life easier, please put your submission directory at the top of the
code printout. Note that you will probably want to add helper
methods ...