











Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
The implementation of various methods related to objecttree and bag data structures in java. The methods include isbalanced, isbst, labelbinaryaddress, labelpreorderaddress, testtree, and teststring. The document also includes instructions for changing the implementation of the nextelement method to enumerate tree elements in post-order and creating a bagentry class. Additionally, there are notes on objecttree and objecttreeops contracts and appendices with their respective contracts.
Typology: Assignments
1 / 19
This page cannot be seen from the preview
Don't miss anything!












CS230 Data Structures Handout # 20 Prof. Lyn Turbak November 3, 2004 Wellesley College
Exam 2 Notice: On Friday, November 12, the second take-home exam will be posted. It will be due at 6pm on Saturday, November 20. This is a hard deadline. No extensions will be given after this time.^1 The exam will cover the material in lecture through Lecture 18 (Mon. November 8) and the material in problem sets through PS6, mainly focusing on material introduced since the last exam: binary trees and contracts and implementations of stacks, queues, priority queues, sets, bags, and tables. Because you should focus on the exam, it is strongly recommended that you submit PS on time, although you may use lateness coupons to turn in PS6 late. But since the exam is worth much more than the problem set, it might be best to cut your losses on PS6 if you are not done with it so that you can focus on the exam.
Overview: The purpose of this assignment is to give you practice with manipulating trees and implementing collections via trees.
Working Together: If you worked with a partner on a previous problem set and want to work with a partner on this assignment, you are encourage to choose a different partner. However, you may also work with someone you worked with in the first half of the semester.
Submission: Each team should turn in a single hardcopy submission packet for all problems by slipping it under Lyn’s office door by 6pm on the due date. The packet should include:
Each team should also submit a single softcopy (consisting of your final ps6 directory) to the drop directory ~cs230/drop/ps6/username, where username is the username of one of the team members (indicate which drop folder you used on your hardcopy header sheet). To do this, execute the following commands in Linux in the account of the team member being used to store the code.
cd /students/username/cs cp -R ps6 ~cs230/drop/ps6/username/ (^1) Especially since the Red Sox season is over!
Problem 1 [40]: ObjectTree Methods In this problem, you will define four methods that manipulate immutable binary trees of objects. Skeletons for these methods appear in the file ps6/PS6TreeOps.java, which you can access after you perform a cvs update -d. For this problem, it is helpful to know a number of definitions. The sample tree T below will be used as an example in many of the definitions:
We adopt the convention of not showing leaf nodes in our tree diagrams.
For example, here is a version of T in which each node has been annotated with its binary address:
Hint: define labelPreOrderAddress in terms of an auxiliary recursive function that takes two arguments – a tree and a pre-order address – and returns a tree. The OT.size() method is particularly helpful here.
Notes:
Problem 2 [20]: Tree Enumerations In class, we have studied various “orders” for traversing the elements of a binary tree: pre-order, in-order, and post-order. In this problem, we shall extend these traversal notions to enumerating the the elements of a binary tree. It turns out that stacks and queues are very helpful for implementing tree enumerations. Figs. 1–2 present the implementation of a InOrderElts class that enumerates the elements of an ObjectTree according to a depth-first, left-to-right in-order traversal. The class has a single instance variable, stk, that holds a stack of non-empty ObjectTrees that intuitively are “still to be processed”. The main method tests InOrderElts in three different ways, according to the nature of arg in java InOrderElts arg:
Enumerating elements of <<<* 4 > 1 << 5 > 2 >> 6 < 3 < 7 *>>> 4 1 5 2 6 3 7
Total number of elements: 7
For example, the breadth-first tree with 12 nodes is:
// ****************************** TESTING ******************************
public static void main (String [] args) { testString(args[0]); }
public static void testString (String s) { // If s is an integer n , create a breadth first tree with n elements: try { testTree(OT.breadthTree(1, Integer.parseInt(s))); } catch (NumberFormatException e1) { // Otherwise, try to parse s as a string tree representation try { testTree(OT.fromString(s)); } catch (Exception e2) { // Otherwise treat as the name of a file, // in which each line is a number, tree rep, or filename Enumeration lines = new FileLines(s); while (lines.hasMoreElements()) { testString((String) lines.nextElement()); } } } }
public static void testTree (ObjectTree t) { System.out.println("------------------------------------------------------------"); System.out.println("Enumerating elements of " + t); EnumTest.test(new InOrderElts(t)); }
// Hack for abbreviating ObjectTree and ObjectTreeOps as OT. private static ObjectTreeOps OT;
}
Figure 2: Implementation of InOrderElts, Part 2.
Here is a test case based on this tree: [cs230@koala ps6] java InOrderElts 12
Enumerating elements of <<<<* 8 > 4 < 9 >> 2 << 10 > 5 < 11 >>> 1 <<< 12 *> 6 > 3 < 7 *>>> 8 4 9 2 10 5 11 1 12 6 3 7 Total number of elements: 12
a. [10]: Understanding InOrderElts In this part, you will show how InOrderElts works in the context of the following tree, which we shall assume is named A^2 : 6
1
4 2
5
Consider the following code: ObjectTree A = ObjectTreeOps.fromString("<<<* 4 > 1 << 5 > 2 >> 6 < 3 < 7 *>>>"); Enumeration e = new InOrderElts(A); while (e.hasMoreElements) { System.out.println(e.nextElement()); } Draw a sequence of “snapshots” of the contents of the stack stk at the beginning of every call to nextElement(). Note that nextElement() is called recursively, and the contents of stk at the beginning of these recursive calls should also be drawn. In your sequence of snapshots, also indicate where a tree value is returned by the enumeration. In this problem, you should draw the elements of a stack from left to right where the leftmost element is the top of the stack and the rightmost element is the bottom of the stack. (^2) Even though the labels look like integers, assume this is an ObjectTree with string values such as "1", "2", etc.
Problem 3 [40]: Mutable BST of Bag Entries Implementation of Bags A bag is a collection of unordered elements that may contain multiple occurrences of each element. In the CS230 collection hierarchy, the Bag interface describes mutable bags. You should study this interface (Appendix D) before proceeding with this problem. In this problem, you will implement a class BagMBSTBagEntries that represents bags as a mutable binary search tree of entries that pair elements in the bag with their number of occurrences. Each entry should be an instance of the following BagEntry class:
public class BagEntry {
public Object elt; public int num;
public BagEntry (Object elt, int num) { this.elt = elt; this.num = num; }
public String toString () { return "BagEntry[" + elt + "," + num + "]"; }
}
To improve the running time of the size() and count() bag operations, the values to be returned by these methods should be cached in instance variables of the BagMBSTEntries class. So instances of BagMBSTEntries should have the following instances variables:
For example, Fig. 3 shows one possible representation of an instance of BagMBSTEntries that contains two As, three Bs and one C. (The shape of the tree is determined by the order in which the elements were inserted.)
BagMBSTEntries entries count 3 size 6 comp ... BagEntry elt B num 3
BagEntry elt A num 2
BagEntry elt C num 1
Figure 3: An example of a BagMBSTEntries instance.
To complete this problem, you need to flesh out the following methods of the bag implementation in BagMBSTEntries.java using the representation described above:
Constructor Methods
public BagMBSTEntries (Comparator c); public BagMBSTEntries ();
Instance Methods
public Object choose(); public void clear(); public Object clone(); public int count(); public boolean delete(Object x); public boolean deleteAll(Object x); public Object deleteOne(); public boolean isMember(Object x); public void insert(Object x); public ObjectList toList(); public int occurrences(Object x); public int size();
Note that many instance methods from the Bag interface in Appendix D are missing from the above list. This is because the BagMBSTEntries class inherits implementations of these other methods from its superclasses. Test your implementation by executing java BagMBSTEntries, which invokes the bag methods on various simple BagMBSTEntries instances. Study the output carefully to make sure that the methods behave as expected. You should turn in the transcript of this test for your final version of the code as part of your hardcopy submission.
public class FindEntryInfo {
public ObjectMTree parent, child; public boolean isChildToLeft; public BagEntry entry;
public FindEntryInfo (ObjectMTree parent, ObjectMTree child, boolean isChildToLeft) { this.parent = parent; this.child = child; this.isChildToLeft = isChildToLeft; if (ObjectMTree.isLeaf(child)) { this.entry = null; } else { this.entry = (BagEntry) ObjectMTree.value(child); } } }
Figure 4: The FindEntryInfo class.
import java.util.Comparator;
public class BagEntryComparator implements Comparator {
private Comparator eltComp;
public BagEntryComparator (Comparator eltComp) { this.eltComp = eltComp; }
public int compare (Object x, Object y) { return eltComp.compare(((BagEntry) x).elt, ((BagEntry) y).elt); }
public boolean equals (Object c) { if (c instanceof BagEntryComparator) { return eltComp.equals(((BagEntryComparator) c).eltComp); } else { return false; } } }
Figure 5: The BagEntryComparator class.
The ObjectTree class models immutable trees whose nodes hold object values.
Public Class Methods:
public static ObjectTree leaf (); Returns a leaf – i.e., a distingushed non-value-bearing node that denotes an empty tree.
public static ObjectTree node (ObjectTree l, Object v, ObjectTree r); Returns a tree node whose left subtree is l, whose value is v, and whose right subtree is r.
public static boolean isLeaf (ObjectTree t); Returns true if t is a leaf and false otherwise (i.e., if t is a tree node).
public static Object value (ObjectTree t); If t is a node, returns the value it holds. If t is a leaf, throws a RuntimeException indicating that a leaf has no value.
public static ObjectTree left (ObjectTree t); If t is a node, returns its left subtree. If t is a leaf, throws a RuntimeException indicating that a leaf has no left subtree.
public static ObjectTree right (ObjectTree t); If t is a node, returns its right subtree. If t is a leaf, throws a RuntimeException indicating that a leaf has no right subtree.
public static String toString (ObjectTree t); Returns the string representation of t (see the description in the toString() instance method).
public static ObjectTree fromString (String s); If s is a string representation of an object tree (see the description in the toString() in- stance method), returns an object tree with string elements whose string representation is s. Otherwise, throws a RuntimeException.
Public Instance Methods:
public String toString (); Returns a string representation of this tree. In this representation, a leaf is represented by
The ObjectMTree class models mutable trees whose nodes hold object values.
Public Class Methods:
public static ObjectMTree leaf (); Returns a leaf – i.e., a distingushed non-value-bearing node that denotes an empty tree.
public static ObjectMTree node (ObjectMTree l, Object v, ObjectMTree r); Returns a tree node whose left subtree is l, whose value is v, and whose right subtree is r.
public static boolean isLeaf (ObjectMTree t); Returns true if t is a leaf and false otherwise (i.e., if t is a tree node).
public static Object value (ObjectMTree t); If t is a node, returns the value it holds. If t is a leaf, throws a RuntimeException indicating that a leaf has no value.
public static ObjectMTree left (ObjectMTree t); If t is a node, returns its left subtree. If t is a leaf, throws a RuntimeException indicating that a leaf has no left subtree.
public static ObjectMTree right (ObjectMTree t); If t is a node, returns its right subtree. If t is a leaf, throws a RuntimeException indicating that a leaf has no right subtree.
public static void setValue (ObjectMTree t, Object newValue); If t is a node, its value is changed to be newValue. If t is a leaf, throws a RuntimeException indicating that a leaf has no value.
public static void setLeft (ObjectMTree t, ObjectMTree newLeft); If t is a node, its left subtree is changed to be newLeft. If t is a leaf, throws a RuntimeException indicating that a leaf has no left subtree.
public static void setRight (ObjectMTree t, ObjectMTree newRight); If t is a node, its right subtree is changed to be newRight. If t is a leaf, throws a RuntimeException indicating that a leaf has no right subtree.
Public Instance Methods:
public String toString (); Returns a string representation of this tree. In this representation, a leaf is represented by
The Bag interface describes mutable collections of unordered elements that may contain multiple occurrences of each element. In mathematics, multiset is a synonym for bag. Each bag instance has a Comparator that is used to determine element equality (and may be used in bag implementations to order elements).
Public Instance Methods Inherited from Collection Interface:
public void insert (Object elt); Modifies this bag by inserting a new occurrence of elt.
public Object deleteFirst (); Deletes and returns an arbitrary element of this bag. Throws a RuntimeException if this bag is empty. The deleteFirst method is a synonym for deleteOne.
public Object first (); Returns an arbitrary element of this bag. Throws a RuntimeException if this bag is empty. The first method is a synonym for choose.
public int size (); Returns the number of element occurrences in this bag.
public boolean isEmpty (); Returns true if this bag has no elements, and false otherwise.
public void clear (); Removes all elements from this bag.
public Object clone (); Returns a ”shallow” copy of this bag – i.e. the copied bag structure is new, but elements themselves are shared with the old bag. Operations on the copied bag do not affect the original bag and vice versa. Operations on mutable elements of the copied bag do affect elements of the original bag, and vice versa.
public Enumeration elements (); Returns an enumeration of the element occurrences in this bag in an arbitrary order.
public ObjectList toList (); Returns a list of the element occurrences in this bag in an arbitrary order.
public String name (); Returns a name indicating the implementation of this bag.
Public Instance Methods Inherited from ComparatorCollection Interface:
public Comparator comparator (); Returns the comparator used by this bag to compare elements.
public boolean delete (Object elt); Deletes one occurrence of elt from this bag. Returns true if elt was a member of the bag and false otherwise.
Problem Set Header Page Please make this the first page of your hardcopy submission.
In the Time column, please estimate the time you or your team spent on the parts of this problem set. Team members should be working closely together, so it will be assumed that the time reported is the time for each team member. Please try to be as accurate as possible; this information will help me design future problem sets. I will fill out the Score column when grading your problem set.