Computer Science 245: Data Structures and Algorithms

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:
The file BinarySearchTree.java already has "stubs" for ElementAt, NumLarger, 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!).

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/