CSC 207 Grinnell College Fall, 2014
 
Algorithms and Object-Oriented Design
 

An Introduction to Trees in Java

Goals

This lab considers a binary search tree as a specific type of tree and provides practice with how such a tree structure might be implemented in Java.

Background

  1. Review the readings for this lab regarding the basic defintions of general trees and binary search trees.

  2. Which of the following trees is(are) a binary search tree(s)?

Several trees

Implementing Binary Search Trees in Java

The implementation of a binary search tree in Java follows a similar approach to our implementation of lists.

This lab's readings discuss the approaches and implementations for each of these Java classes.

  1. Import the following classes into a trees package within eclipse.

    Compile and run the tests provided within DirectoryBST.

  2. What can you say about the order of the entries printed by the print method? Explain why this sequence is obtained.

The discussion of insertion into a binary search tree in the reading for this lab described the insertion of the number 153 into the following tree (which repeats the tree given above).

A BSTree Object
  1. Suppose a similar insert method was used to build the tree in the above example (with numbers 23, 37, 48, 96, 123, 185, 200, 285, and 309 rather than names and entries).

    1. What data do you think would have to be inserted first into the null tree?
    2. What item or items might have been inserted next?
    3. What flexibility might there be in the order of entering data to get the above tree, and what restrictions might apply?

    Explain your answers.

  2. Given the order of insertions in the main method of DirectoryBST, draw a picture of the binary search tree that is produced by that program.

Additional Practice

  1. Write an iterative version of the recursive lookup method.

  2. Use ideas from print to write a printLeaves method, which prints just the leaves within a tree. Here, one can still traverse the full tree -- but printing should occur only if a node has only null left and right subtrees.

  3. Ideas from print also can be used to count the number of (non null) nodes in a tree. Use this approach to write a countNodes method.

  4. The height of a tree is the maximum number of levels of nodes within the tree; by convention, the height of a tree with only one node is 0. Thus, the binary search tree shown between parts 4 and 5 above (with root 123) has height 3. Add to the BSTree class a method height which computes the height of a tree.


This document is available on the World Wide Web as

http://www.walker.cs.grinnell.edu/courses/207.sp12/labs/lab-intro-trees.shtml

created 18 April 2000
last revised 24 March 2005
last revised 4-5 April 2012
Valid HTML 4.01! Valid CSS!
For more information, please contact Henry M. Walker at walker@cs.grinnell.edu.