CSci 160 Lab 3: Recursion Removal in the BST Class: Part I

Objectives

To remove the recursion in the binary search tree implementation. Non-recursive methods are generally more efficient. This week we will take care of insertion; next week, deletion.

Exercises

  1. Download the code for the BinarySearchTree class. Put it in a BlueJ project.
  2. Before you run it, note that the main method uses a command-line argument. In BlueJ, when running such a main method, you need to enter the command-line argument in between the brackets ("{}") in quotes (e.g., "40"). (At the command line, typing java BinarySearchTree 40 (no quotes around the 40 in that case) has the same effect.) The main method then inserts that many random elements into the tree.
  3. Okay, now run it and familiarize yourself with the main method.
  4. Modify this public method:

    public void insert( AnyType x ) { root = insert( x, root ); }

    so that it doesn't use the private recursive method:

    private BinaryNode<AnyType> insert( AnyType x, BinaryNode<AnyType> t )
    { .... }

    Instead, the public version of insert should use a while-loop to search for the element. Note that there should be no use of recursion in this public method.

  5. What kind of a difference does this make? It doesn't change the big-O runtime of the algorithm. But it does change the time. To see this, compare the runtime of the non-recursive and recursive insert() method. To time something, you just use this template:
                time = (double) ( System.currentTimeMillis( ) );
                //whatever it is you want to time
                time = (double) ( System.currentTimeMillis( ) ) - time;
    
Hand in: Electronic submissions of the modified programs, with changes indicated clearly via comments. Also, in comments at the beginning of the program, give reports of your results and explain why the big-O runtime is the same in the recursive and iterative versions, and why the absolute runtime is different.

Save your work! You will need it for the next lab!
Last modified: 9/20/10 by Frederic Green.