CS210: Intermediate Computing/Data Structures (Java)

Lab #9

Purpose

This lab gives you experience implementing a right and left rotation on a binary tree.

Pre-Lab Assignment

Complete and test the code for your iteratorLevelOrder method from Lab 8.

 

Study the right and left rotation algorithms given in L&C, page 411-412 so that you understand the design of the methods that you will need to implement in this lab.

 

Prior to the lab session, do the following to get started:

Download, save, and unzip the file Lab9.zip on your removable media (floppy disk, Zip disk, or memory stick) creating a directory named Lab9.

Open the Dr Java Application on your PC. 

Create a new Dr Java project in the Lab9 directory by selecting the menu Project -> New… naming the project file Lab9 and saving it in your new Lab9 directory.  (Dr Java automatically opens an Untitled file in the editor window which you will ignore.)

Using the menu File-> Open, open and save the files: BinaryTreeADT.java, BinaryTreeNode.java, and Rotation.java.  Dr Java will automatically include these source files in the Project.  Add your LinkedBinaryTree.java file from Lab 8 to the directory and open/save it to include it in the Dr Java project.  Use the menu Project -> Save to save the updated project file. 

Lab Activities

The Rotation class has the main method.  Its main method sets up two test case binary trees using the LinkedBinaryTree class and calls the LinkedBinaryTree class methods rotateRight and rotateLeft (that you will write below) to rotate the root of each test case tree.  It uses the Iterator object returned by the iteratorLevelOrder method to print the contents of each tree both before and after its rotation.

 

You need to design and add code for two new methods of the LinkedBinaryTree class where indicated. 

 

1.  In rotateRight, write code to implement the right rotation algorithm in the L&C text on page 411.

 

2.  In rotateLeft, write code to implement the left rotation algorithm in the L&C text on page 412.

 

A sample run of the finished program for the right rotation is shown here:

 

> java Rotation

Contents of rightTree before right rotation

13

7

15

5

10

null

null

3

null

null

null

null

null

Contents of rightTree after right rotation

7

5

13

3

null

10

15

null

null

null

null

null

null

. . .

Report

In your report, explain when you would want to use the rotateRight or rotateLeft methods and how your code could determine that it needed to do one of these two rotations.