SlideShare a Scribd company logo
1 of 60
Consider this code using the ArrayBag of Section 5.2 and the
Location class from Chapter 2. What is the output?
Location i = new Location(0, 3);
Location j = new Location(0, 3);
b.add(i);
b.add(j);
System.out.println(b.countOccurrences(i));
A. 0
B. 1
C. 2
D. 3
Suppose that b and c are Integer objects. A typical use of the
clone method looks like this:
b = (Integer) c.clone( );
Write a short clear explanation of why the (Integer) type cast is
required in this typical example.
A. obj = s;
B. s = obj;
C. s = (String) obj;
D. Two or more answers are correct.
Suppose that obj is an Object variable and s is a String variable.
Which of the following statements
is a correctly-compiling widening conversion? Don't worry
about possible run-time exceptions
A. obj = s;
B. s = obj;
C. s = (String) obj;
D. Two or more answers are correct.
Suppose that x and y are reference variables and a program
activates x.equals(y). What occurs if x is the null reference?
A. A NullPointerException occurs
B. It always returns true.
C. It always returns false.
D. It returns true if y is also a null reference; otherwise
it returns false.
Consider the implementation of the Stack using a partially-
filled array.
What goes wrong if we try to store the top of the Stack at
location [0] and the bottom of the Stack at the last used position
of the array?
A. Both peek and pop would require linear time.
B. Both push and pop would require linear time.
C. The Stack could not be used to check balanced
parentheses.
D. The Stack could not be used to evaluate postfix
expressions.
Write some lines of code that declares an Integer object, using
the Integer wrapper class.
Assign the value 42 to this object, then copy this value from the
Integer object to an ordinary int variable.
Consider the usual algorithm for determining whether a
sequence of parentheses is balanced.
What is the maximum number of parentheses that will appear on
the stack AT ANY ONE TIME when the algorithm analyzes:
(()(())(()))?
A. 1
B. 2
C. 3
D. 4
E. 5 or more
Consider the usual algorithm to convert an infix expression to a
postfix expression.
Suppose that you have read 10 input characters during a
conversion and that the
stack now contains the symbols as shown below. Suppose that
you read and process
the 11th symbol of the input. What symbol is at the top of the
stack in the case where
the 11th symbol is each of the choices shown?
Which of the following stack operations could result in stack
underflow?
Answer
A. is_empty
B. pop
C. push
D. Two or more of the above answers
What is the value of the postfix expression 6 3 2 4 + - *:
Answer
A. Something between -15 and -100
B. Something between -5 and -15
C. Something between 5 and -5
D. Something between 5 and 15
E. Something between 15 and 100
1. An array of queues can be used to implement a priority
queue, with each possible priority corresponding to its own
element in the array. When is this implementation not feasible?
Answer
A.
When the number of possible priorities is huge.
B.
When the number of possible priorities is small.
C.
When the queues are implemented using a linked list.
D.
When the queues are implemented with circular arrays.
Consider the implementation of the Queue using a circular
array. What goes wrong if we try to keep all the items at the
front of a partially-filled array (so that data[0] is always the
front).
Answer
A.
The constructor would require linear time.
B.
The getFront method would require linear time.
C.
The insert method would require linear time.
D.
The isEmpty method would require linear time.
If data is a circular array of CAPACITY elements, and rear is an
index into that array, what is the formula for the index after
rear?
Answer
A. (rear % 1) + CAPACITY
B. rear % (1 + CAPACITY)
C. (rear + 1) % CAPACITY
D. rear + (1 % CAPACITY)
In the linked-list version of the Queue class, which operations
require linear time for their worst-case behavior?
Answer
A. getFront
B. insert
C. isEmpty
D. None of these operations require linear time.
Which of the following expressions evaluates to true with
approximate probability equal to P? (P is double and 0 <= P <=
1).
Answer
A. Math.random() < P
B. Math.random() > P
C. Math.random() < P * 100
D. Math.random() > P * 100
Consider the following method:
public static void test_a(int n)
{
System.out.println(n + " ");
if (n>0)
test_a(n-2);
}
What is printed by the call test_a(4)?
A. 0 2 4
B. 0 2
C. 2 4
D. 4 2
E. 4 2 0
Consider the following method:
public static boolean deadend()
// Postcondition: The return value is true if the direction
directly
// in front is a dead end (i.e., a direction that cannot contain the
// tapestry).
{
return inquire("Are you facing a wall?") || inquire("Is your
name written in front of you?");
}
Explain why the method deadend sometimes asks 2 questions
and sometimes asks only 1.
Consider the following method:
void superWriteVertical(int number)
// Postcondition: The digits of the number have been written,
// stacked vertically. If number is negative, then a negative
// sign appears on top.
{
if (number < 0)
{
System.out.println("-");
superWriteVertical(-number);
}
else if (number < 10)
System.out.println(number);
else
{
superWriteVertical(number / 10);
System.out.println(number % 10);
}
}
What values of number are directly handled by the stopping
case?
Suppose you are exploring a rectangular maze containing 10
rows and 20 columns. What is the maximum depth of recursion
that can result if you start at the entrance and call
traverse_maze?
What property of fractals lends itself to recursive thinking?
When the compiler compiles your program, how is a recursive
call treated differently than a non-recursive method call?
For this project, write a program that stores integers in a binary
search tree.
The tree should use the BTNode class which is provided.
Write a test program that generates 20 random numbers in the
range of -50 to 50 to build the tree and then uses preorderPrint,
inorderPrint, and postOrderPrint to display the contents of the
tree.
To get an A implement a new method for the BTNode class
which creates a Java vector class to contain
the data from all the nodes in the tree. The specification for
this method is provided in the BTNode file.
Details about the Java vector class are provided in Appendix D,
although the only vector method you'll use is addElement.
Also specify and implement in-order and post-order traversals
and answer the question which of the
three new methods creates a vector with the entries sorted from
smallest to largest?
Your test program should display the vectors created by your
new methods rather than the print methods of BTNode.
// File: BTNode.java from the package edu.colorado.nodes
// Complete documentation is available from the BTNode link
in:
// http://www.cs.colorado.edu/~main/docs/
package BTNode;
import java.util.Vector;
/****************************************************
**************************
* A <CODE>BTNode&lt;<E&gt;</CODE> provides a node for
a binary tree. Each node
* contains a piece of data (which is a reference to an E object)
and references
* to a left and right child. The references to children may be
null to indicate
* that there is no child. The reference stored in a node can also
be null.
*
* <dl><dt><b>Limitations:</b> <dd>
* Beyond <CODE>Int.MAX_VALUE</CODE> elements,
<CODE>treeSize</CODE>, is
* wrong.
*
* <dt><b>Java Source Code for this class:</b><dd>
* <A HREF="../../../../edu/colorado/nodes/BTNode.java">
*
http://www.cs.colorado.edu/~main/edu/colorado/nodes/BTNode.
java </A>
*
* @author Michael Main
* <A HREF="mailto:[email protected]"> ([email protected])
</A>
*
* @version
* Jul 22, 2005
*****************************************************
*************************/
public class BTNode<E>
{
// Invariant of the BTNode<E> class:
// 1. Each node has one reference to an E Object, stored in
the instance
// variable data.
// 2. The instance variables left and right are references to
the node's
// left and right children.
private E data;
private BTNode<E> left, right;
/**
* Initialize a <CODE>BTNode</CODE> with a specified
initial data and links
* children. Note that a child link may be the null reference,
* which indicates that the new node does not have that child.
* @param <CODE>initialData</CODE>
* the initial data of this new node
* @param <CODE>initialLeft</CODE>
* a reference to the left child of this new node--this
reference may be null
* to indicate that there is no node after this new node.
* @param <CODE>initialRight</CODE>
* a reference to the right child of this new node--this
reference may be null
* to indicate that there is no node after this new node.
* <dt><b>Postcondition:</b><dd>
* This node contains the specified data and links to its
children.
**/
public BTNode(E initialData, BTNode<E> initialLeft,
BTNode<E> initialRight)
{
data = initialData;
left = initialLeft;
right = initialRight;
}
/**
* Accessor method to get the data from this node.
* @param - none
* @return
* the data from this node
**/
public E getData( )
{
return data;
}
/**
* Accessor method to get a reference to the left child of this
node.
* @param - none
* @return
* a reference to the left child of this node (or the null
reference if there
* is no left child)
**/
public BTNode<E> getLeft( )
{
return left;
}
/**
* Accessor method to get the data from the leftmost node of
the tree below
* this node.
* @param - none
* @return
* the data from the deepest node that can be reached from
this node by
* following left links.
**/
public E getLeftmostData( )
{
if (left == null)
return data;
else
return left.getLeftmostData( );
}
/**
* Accessor method to get a reference to the right child of this
node.
* @param - none
* @return
* a reference to the right child of this node (or the null
reference if there
* is no right child)
**/
public BTNode<E> getRight( )
{
return right;
}
/**
* Accessor method to get the data from the rightmost node of
the tree below
* this node.
* @param - none
* @return
* the data from the deepest node that can be reached from
this node by
* following right links.
**/
public E getRightmostData( )
{
if (left == null)
return data;
else
return left.getRightmostData( );
}
/**
* Uses an inorder traversal to print the data from each node at
or below
* this node of the binary tree.
* @param - none
* <dt><b>Postcondition:</b><dd>
* The data of this node and all its descendants have been
writeen by
* <CODE>System.out.println( )</CODE> using an inorder
traversal.
**/
public void inorderPrint( )
{
if (left != null)
left.inorderPrint( );
System.out.println(data);
if (right != null)
right.inorderPrint( );
}
/**
* Accessor method to determine whether a node is a leaf.
* @param - none
* @return
* <CODE>true</CODE> (if this node is a leaf) or
* <CODE>false</CODE> (if this node is not a leaf.
**/
public boolean isLeaf( )
{
return (left == null) && (right == null);
}
/**
* Uses a preorder traversal to print the data from each node at
or below
* this node of the binary tree.
* @param - none
* <dt><b>Postcondition:</b><dd>
* The data of this node and all its descendants have been
writeen by
* <CODE>System.out.println( )</CODE> using a preorder
traversal.
**/
public void preorderPrint( )
{
System.out.println(data);
if (left != null)
left.preorderPrint( );
if (right != null)
right.preorderPrint( );
}
/**
* Uses a postorder traversal to print the data from each node
at or below
* this node of the binary tree.
* @param - none
* <dt><b>Postcondition:</b><dd>
* The data of this node and all its descendants have been
writeen by
* <CODE>System.out.println( )</CODE> using a postorder
traversal.
**/
public void postorderPrint( )
{
if (left != null)
left.postorderPrint( );
if (right != null)
right.postorderPrint( );
System.out.println(data);
}
/**
* Uses an inorder traversal to print the data from each node at
or below
* this node of the binary tree, with indentations to indicate
the depth
* of each node.
* @param <CODE>depth</CODE>
* the depth of this node (with 0 for root, 1 for the root's
* children, and so on)(
* <dt><b>Precondition:</b><dd>
* <CODE>depth</CODE> is the depth of this node.
* <dt><b>Postcondition:</b><dd>
* The data of this node and all its descendants have been
writeen by
* <CODE>System.out.println( )</CODE> using an inorder
traversal.
* The indentation of each line of data is four times its depth
in the
* tree. A dash "--" is printed at any place where a child has
no
* sibling.
**/
public void print(int depth)
{
int i;
// Print the indentation and the data from the current node:
for (i = 1; i <= depth; i++)
System.out.print(" ");
System.out.println(data);
// Print the left subtree (or a dash if there is a right child
and no left child)
if (left != null)
left.print(depth+1);
else if (right != null)
{
for (i = 1; i <= depth+1; i++)
System.out.print(" ");
System.out.println("--");
}
// Print the right subtree (or a dash if there is a left child
and no left child)
if (right != null)
right.print(depth+1);
else if (left != null)
{
for (i = 1; i <= depth+1; i++)
System.out.print(" ");
System.out.println("--");
}
}
/**
* Remove the leftmost most node of the tree with this node as
its root.
* @param - none
* <dt><b>Postcondition:</b><dd>
* The tree starting at this node has had its leftmost node
removed (i.e.,
* the deepest node that can be reached by following left
links). The
* return value is a reference to the root of the new (smaller)
tree.
* This return value could be null if the original tree had only
one
* node (since that one node has now been removed).
**/
public BTNode<E> removeLeftmost( )
{
if (left == null)
return right;
else
{
left = left.removeLeftmost( );
return this;
}
}
/**
* Remove the rightmost most node of the tree with this node
as its root.
* @param - none
* <dt><b>Postcondition:</b><dd>
* The tree starting at this node has had its rightmost node
removed (i.e.,
* the deepest node that can be reached by following right
links). The
* return value is a reference to the root of the new (smaller)
tree.
* This return value could be null if the original tree had only
one
* node (since that one node has now been removed).
**/
public BTNode<E> removeRightmost( )
{
if (right == null)
return left;
else
{
right = right.removeRightmost( );
return this;
}
}
/**
* Modification method to set the data in this node.
* @param <CODE>newData</CODE>
* the new data to place in this node
* <dt><b>Postcondition:</b><dd>
* The data of this node has been set to
<CODE>newData</CODE>.
**/
public void setData(E newData)
{
data = newData;
}
/**
* Modification method to set the link to the left child of this
node.
* @param <CODE>newLeft</CODE>
* a reference to the node that should appear as the left child
of this node
* (or the null reference if there is no left child for this node)
* <dt><b>Postcondition:</b><dd>
* The link to the left child of this node has been set to
<CODE>newLeft</CODE>.
* Any other node (that used to be the left child) is no longer
connected to
* this node.
**/
public void setLeft(BTNode<E> newLeft)
{
left = newLeft;
}
/**
* Modification method to set the link to the right child of this
node.
* @param <CODE>newLeft</CODE>
* a reference to the node that should appear as the right
child of this node
* (or the null reference if there is no right child for this
node)
* <dt><b>Postcondition:</b><dd>
* The link to the right child of this node has been set to
<CODE>newRight</CODE>.
* Any other node (that used to be the right child) is no
longer connected to
* this node.
**/
public void setRight(BTNode<E> newRight)
{
right = newRight;
}
/**
* Copy a binary tree.
* @param <CODE>source</CODE>
* a reference to the root of a binary tree that will be copied
(which may be
* an empty tree where <CODE>source</CODE> is null)
* @return
* The method has made a copy of the binary tree starting at
* <CODE>source</CODE>. The return value is a reference
to the root of the copy.
* @exception OutOfMemoryError
* Indicates that there is insufficient memory for the new
tree.
**/
public static <E> BTNode<E> treeCopy(BTNode<E> source)
{
BTNode<E> leftCopy, rightCopy;
if (source == null)
return null;
else
{
leftCopy = treeCopy(source.left);
rightCopy = treeCopy(source.right);
return new BTNode<E>(source.data, leftCopy,
rightCopy);
}
}
/**
* Count the number of nodes in a binary tree.
* @param <CODE>root</CODE>
* a reference to the root of a binary tree (which may be
* an empty tree where <CODE>source</CODE> is null)
* @return
* the number of nodes in the binary tree
* <dt><b>Note:</b><dd>
* A wrong answer occurs for trees larger than
* <CODE>INT.MAX_VALUE</CODE>.
**/
public static <E> long treeSize(BTNode<E> root)
{
if (root == null)
return 0;
else
return 1 + treeSize(root.left) + treeSize(root.right);
}
/**
* The method does a pre-order traversal of all nodes at or
below this node,
* appending the data from each node to a Vector
* @param v
* the Vector that will have data appended to it
* @precondition
* The node and all its descendants have been traversed with a
pre-order
* traversal, and all data has been apended to v using
v.addElement
* @postcondition
* The node and all its descendants have been traversed with a
pre-order
* traversal, and all data has been appended to v using
v.addElement.
* @throws NullPointerException
* Indicates that v is null.
*
*/
public void preorderVector(Vector<E> v){
}
}
// FILE: AnimalGuess.java
// This animal-guessing program illustrates the use of the binary
tree node class.
import edu.colorado.nodes.BTNode;
import java.util.Scanner;
/****************************************************
**************************
* The <CODE>AnimalGuess</CODE> Java application
illustrates the use of
* the binary tree node class is a small animal-guessing game.
*
* <p><dt><b>Java Source Code for this class:</b><dd>
* <A HREF="../applications/Animals.java">
* http://www.cs.colorado.edu/~main/applications/Animals.java
* </A>
*
* @author Michael Main
* <A HREF="mailto:[email protected]"> ([email protected])
</A>
*
* @version
* Jul 22, 2005
*****************************************************
*************************/
public class AnimalGuess
{
private static Scanner stdin = new Scanner(System.in);
/**
* The main method prints instructions and repeatedly plays
the
* animal-guessing game. As the game is played, the taxonomy
tree
* grows by learning new animals. The
<CODE>String</CODE> argument
* (<CODE>args</CODE>) is not used in this implementation.
**/
public static void main(String[ ] args)
{
BTNode<String> root;
instruct( );
root = beginningTree( );
do
play(root);
while (query("Shall we play again?"));
System.out.println("Thanks for teaching me a thing or
two.");
}
/**
* Print instructions for the animal-guessing game.
**/
public static void instruct( )
{
System.out.println("Please think of an animal.");
System.out.println("I will ask some yes/no questions to try
to figure");
System.out.println("out what you are.");
}
/**
* Play one round of the animal guessing game.
* @param <CODE>current</CODE>
* a reference to the root node of a binary taxonomy tree that
will be
* used to play the game.
* <dt><b>Postcondition:</b><dd>
* The method has played one round of the game, and
possibly
* added new information about a new animal.
* @exception java.lang.OutOfMemoryError
* Indicates that there is insufficient memory to add new
* information to the tree.
**/
public static void play(BTNode<String> current)
{
while (!current.isLeaf( ))
{
if (query(current.getData( )))
current = current.getLeft( );
else
current = current.getRight( );
}
System.out.print("My guess is " + current.getData( ) + ". ");
if (!query("Am I right?"))
learn(current);
else
System.out.println("I knew it all along!");
}
/**
* Construct a small taxonomy tree with four animals.
* @param - none
* @return
* a reference to the root of a taxonomy tree with the
animals:
* kangaroo, mouse, trout, robin.
* @exception OutOfMemoryError
* Indicates that there is insufficient memory to create the
tree.
**/
public static BTNode<String> beginningTree( )
{
BTNode<String> root;
BTNode<String> child;
final String ROOT_QUESTION = "Are you a mammal?";
final String LEFT_QUESTION = "Are you bigger than a
cat?";
final String RIGHT_QUESTION = "Do you live
underwater?";
final String ANIMAL1 = "Kangaroo";
final String ANIMAL2 = "Mouse";
final String ANIMAL3 = "Trout";
final String ANIMAL4 = "Robin";
// Create the root node with the question “Are you a
mammal?”
root = new BTNode<String>(ROOT_QUESTION, null,
null);
// Create and attach the left subtree.
child = new BTNode<String>(LEFT_QUESTION, null,
null);
child.setLeft(new BTNode<String>(ANIMAL1, null, null));
child.setRight(new BTNode<String>(ANIMAL2, null,
null));
root.setLeft(child);
// Create and attach the right subtree.
child = new BTNode<String>(RIGHT_QUESTION, null,
null);
child.setLeft(new BTNode<String>(ANIMAL3, null, null));
child.setRight(new BTNode<String>(ANIMAL4, null,
null));
root.setRight(child);
return root;
}
/**
* Elicits information from the user to improve a binary
taxonomy tree.
* @param <CODE>current</CODE>
* a reference to a leaf node of a binary taxonomy tree
* <dt><b>Precondition:</b><dd>
* <CODE>current</CODE> is a reference to a leaf in a
binary
* taxonomy tree
* <dt><b>Postcondition:</b><dd>
* Information has been elicited from the user, and the tree
has
* been improved.
* @exception OutOfMemoryError
* Indicates that there is insufficient memory to add new
* information to the tree.
**/
public static void learn(BTNode<String> current)
// Precondition: current is a reference to a leaf in a taxonomy
tree. This
// leaf contains a wrong guess that was just made.
// Postcondition: Information has been elicited from the user,
and the tree
// has been improved.
{
String guessAnimal; // The animal that was just guessed
String correctAnimal; // The animal that the user was
thinking of
String newQuestion; // A question to distinguish the two
animals
// Set Strings for the guessed animal, correct animal and a
new question.
guessAnimal = current.getData( );
System.out.println("I give up. What are you? ");
correctAnimal = stdin.nextLine( );
System.out.println("Please type a yes/no question that will
distinguish a");
System.out.println(correctAnimal + " from a " +
guessAnimal + ".");
newQuestion = stdin.nextLine( );
// Put the new question in the current node, and add two
new children.
current.setData(newQuestion);
System.out.println("As a " + correctAnimal + ", " +
newQuestion);
if (query("Please answer"))
{
current.setLeft(new BTNode<String>(correctAnimal, null,
null));
current.setRight(new BTNode<String>(guessAnimal, null,
null));
}
else
{
current.setLeft(new BTNode<String>(guessAnimal, null,
null));
current.setRight(new BTNode<String>(correctAnimal,
null, null));
}
}
public static boolean query(String prompt)
{
String answer;
System.out.print(prompt + " [Y or N]: ");
answer = stdin.nextLine( ).toUpperCase( );
while (!answer.startsWith("Y") &&
!answer.startsWith("N"))
{
System.out.print("Invalid response. Please type Y or N:
");
answer = stdin.nextLine( ).toUpperCase( );
}
return answer.startsWith("Y");
}
}
// File: IntTreeBag.java from the package
edu.colorado.collections
// The implementation of most methods in this file is left as a
student
// exercise from Section 9.5 of "Data Structures and Other
Objects Using Java"
// Check with your instructor to see whether you should put this
class in
// a package. At the moment, it is declared as part of
edu.colorado.collections:
package edu.colorado.collections;
import edu.colorado.nodes.IntBTNode;
/****************************************************
**************************
* This class is a homework assignment;
* An <CODE>IntTreeBag</CODE> is a collection of int
numbers.
*
* <dl><dt><b>Limitations:</b> <dd>
* Beyond <CODE>Integer.MAX_VALUE</CODE> elements,
<CODE>countOccurrences</CODE>,
* and <CODE>size</CODE> are wrong.
*
* <dt><b>Outline of Java Source Code for this class:</b><dd>
* <A
HREF="../../../../edu/colorado/collections/IntTreeBag.java">
*
http://www.cs.colorado.edu/~main/edu/colorado/collections/Int
TreeBag.java
* </A>
*
* <dt><b>Note:</b><dd>
* This file contains only blank implementations ("stubs")
* because this is a Programming Project for my students.
*
* @version
* Jan 24, 1999
*
* @see IntArrayBag
* @see IntLinkedBag
*****************************************************
*************************/
public class IntTreeBag implements Cloneable
{
// Invariant of the IntTreeBag class:
// 1. The elements in the bag are stored in a binary search
tree.
// 2. The instance variable root is a reference to the root of
the
// binary search tree (or null for an empty tree).
private IntBTNode root;
/**
* Insert a new element into this bag.
* @param <CODE>element</CODE>
* the new element that is being inserted
* <dt><b>Postcondition:</b><dd>
* A new copy of the element has been added to this bag.
* @exception OutOfMemoryError
* Indicates insufficient memory a new IntBTNode.
**/
public void add(int element)
{
// Implemented by student.
}
/**
* Add the contents of another bag to this bag.
* @param <CODE>addend</CODE>
* a bag whose contents will be added to this bag
* <dt><b>Precondition:</b><dd>
* The parameter, <CODE>addend</CODE>, is not null.
* <dt><b>Postcondition:</b><dd>
* The elements from <CODE>addend</CODE> have been
added to this bag.
* @exception IllegalArgumentException
* Indicates that <CODE>addend</CODE> is null.
* @exception OutOfMemoryError
* Indicates insufficient memory to increase the size of the
bag.
**/
public void addAll(IntTreeBag addend)
{
// Implemented by student.
}
/**
* Generate a copy of this bag.
* @param - none
* @return
* The return value is a copy of this bag. Subsequent changes
to the
* copy will not affect the original, nor vice versa. Note that
the return
* value must be type cast to an
<CODE>IntTreeBag</CODE> before it can be used.
* @exception OutOfMemoryError
* Indicates insufficient memory for creating the clone.
**/
public Object clone( )
{ // Clone an IntTreeBag object.
// Student will replace this return statement with their own
code:
return null;
}
/**
* Accessor method to count the number of occurrences of a
particular element
* in this bag.
* @param <CODE>target</CODE>
* the element that needs to be counted
* @return
* the number of times that <CODE>target</CODE> occurs
in this bag
**/
public int countOccurrences(int target)
{
// Student will replace this return statement with their own
code:
return 0;
}
/**
* Remove one copy of a specified element from this bag.
* @param <CODE>target</CODE>
* the element to remove from the bag
* <dt><b>Postcondition:</b><dd>
* If <CODE>target</CODE> was found in the bag, then one
copy of
* <CODE>target</CODE> has been removed and the method
returns true.
* Otherwise the bag remains unchanged and the method
returns false.
**/
private boolean remove(int target)
{
// Student will replace this return statement with their own
code:
return false;
}
/**
* Determine the number of elements in this bag.
* @param - none
* @return
* the number of elements in this bag
**/
public int size( )
{
return IntBTNode.treeSize(root);
}
/**
* Create a new bag that contains all the elements from two
other bags.
* @param <CODE>b1</CODE>
* the first of two bags
* @param <CODE>b2</CODE>
* the second of two bags
* <dt><b>Precondition:</b><dd>
* Neither b1 nor b2 is null.
* @return
* the union of b1 and b2
* @exception IllegalArgumentException
* Indicates that one of the arguments is null.
* @exception OutOfMemoryError
* Indicates insufficient memory for the new bag.
**/
public static IntTreeBag union(IntTreeBag b1, IntTreeBag b2)
{
// Student will replace this return statement with their own
code:
return null;
}
}

More Related Content

Similar to Consider this code using the ArrayBag of Section 5.2 and the Locat.docx

Lewis jssap3 e_labman02
Lewis jssap3 e_labman02Lewis jssap3 e_labman02
Lewis jssap3 e_labman02auswhit
 
B61301007 matlab documentation
B61301007 matlab documentationB61301007 matlab documentation
B61301007 matlab documentationManchireddy Reddy
 
1183 c-interview-questions-and-answers
1183 c-interview-questions-and-answers1183 c-interview-questions-and-answers
1183 c-interview-questions-and-answersAkash Gawali
 
queuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbb
queuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbbqueuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbb
queuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbbRAtna29
 
Objectives Assignment 09 Applications of Stacks COS.docx
Objectives Assignment 09 Applications of Stacks COS.docxObjectives Assignment 09 Applications of Stacks COS.docx
Objectives Assignment 09 Applications of Stacks COS.docxdunhamadell
 
Orthogonal Functional Architecture
Orthogonal Functional ArchitectureOrthogonal Functional Architecture
Orthogonal Functional ArchitectureJohn De Goes
 
Mcq 15-20Q15Which of the following trees are binary search tr
Mcq 15-20Q15Which of the following trees are binary search trMcq 15-20Q15Which of the following trees are binary search tr
Mcq 15-20Q15Which of the following trees are binary search trAbramMartino96
 
C++ Programming Homework Help
C++ Programming Homework HelpC++ Programming Homework Help
C++ Programming Homework HelpC++ Homework Help
 
Need done for Date Structures please! 4-18 LAB- Sorted number list imp.pdf
Need done for Date Structures please! 4-18 LAB- Sorted number list imp.pdfNeed done for Date Structures please! 4-18 LAB- Sorted number list imp.pdf
Need done for Date Structures please! 4-18 LAB- Sorted number list imp.pdfinfo114
 
C++aptitude questions and answers
C++aptitude questions and answersC++aptitude questions and answers
C++aptitude questions and answerssheibansari
 
Abstract Data Types (a) Explain briefly what is meant by the ter.pdf
Abstract Data Types (a) Explain briefly what is meant by the ter.pdfAbstract Data Types (a) Explain briefly what is meant by the ter.pdf
Abstract Data Types (a) Explain briefly what is meant by the ter.pdfkarymadelaneyrenne19
 
Java level 1 Quizzes
Java level 1 QuizzesJava level 1 Quizzes
Java level 1 QuizzesSteven Luo
 
Java concepts and questions
Java concepts and questionsJava concepts and questions
Java concepts and questionsFarag Zakaria
 
Data Structure.pdf
Data Structure.pdfData Structure.pdf
Data Structure.pdfMemeMiner
 
Linear Data Structures_SSD.pdf
Linear Data Structures_SSD.pdfLinear Data Structures_SSD.pdf
Linear Data Structures_SSD.pdfssuser37b0e0
 
1z0 804 exam-java se 7 programmer ii
1z0 804 exam-java se 7 programmer ii1z0 804 exam-java se 7 programmer ii
1z0 804 exam-java se 7 programmer iiIsabella789
 

Similar to Consider this code using the ArrayBag of Section 5.2 and the Locat.docx (20)

Lewis jssap3 e_labman02
Lewis jssap3 e_labman02Lewis jssap3 e_labman02
Lewis jssap3 e_labman02
 
B61301007 matlab documentation
B61301007 matlab documentationB61301007 matlab documentation
B61301007 matlab documentation
 
1183 c-interview-questions-and-answers
1183 c-interview-questions-and-answers1183 c-interview-questions-and-answers
1183 c-interview-questions-and-answers
 
queuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbb
queuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbbqueuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbb
queuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbb
 
Objectives Assignment 09 Applications of Stacks COS.docx
Objectives Assignment 09 Applications of Stacks COS.docxObjectives Assignment 09 Applications of Stacks COS.docx
Objectives Assignment 09 Applications of Stacks COS.docx
 
Orthogonal Functional Architecture
Orthogonal Functional ArchitectureOrthogonal Functional Architecture
Orthogonal Functional Architecture
 
Mcq 15-20Q15Which of the following trees are binary search tr
Mcq 15-20Q15Which of the following trees are binary search trMcq 15-20Q15Which of the following trees are binary search tr
Mcq 15-20Q15Which of the following trees are binary search tr
 
C++ Programming Homework Help
C++ Programming Homework HelpC++ Programming Homework Help
C++ Programming Homework Help
 
Need done for Date Structures please! 4-18 LAB- Sorted number list imp.pdf
Need done for Date Structures please! 4-18 LAB- Sorted number list imp.pdfNeed done for Date Structures please! 4-18 LAB- Sorted number list imp.pdf
Need done for Date Structures please! 4-18 LAB- Sorted number list imp.pdf
 
C++aptitude questions and answers
C++aptitude questions and answersC++aptitude questions and answers
C++aptitude questions and answers
 
1
11
1
 
Abstract Data Types (a) Explain briefly what is meant by the ter.pdf
Abstract Data Types (a) Explain briefly what is meant by the ter.pdfAbstract Data Types (a) Explain briefly what is meant by the ter.pdf
Abstract Data Types (a) Explain briefly what is meant by the ter.pdf
 
Lesson 4 stacks and queues
Lesson 4  stacks and queuesLesson 4  stacks and queues
Lesson 4 stacks and queues
 
Java level 1 Quizzes
Java level 1 QuizzesJava level 1 Quizzes
Java level 1 Quizzes
 
Java concepts and questions
Java concepts and questionsJava concepts and questions
Java concepts and questions
 
Lambdas puzzler - Peter Lawrey
Lambdas puzzler - Peter LawreyLambdas puzzler - Peter Lawrey
Lambdas puzzler - Peter Lawrey
 
Data Structure.pdf
Data Structure.pdfData Structure.pdf
Data Structure.pdf
 
Linear Data Structures_SSD.pdf
Linear Data Structures_SSD.pdfLinear Data Structures_SSD.pdf
Linear Data Structures_SSD.pdf
 
1z0 804 exam-java se 7 programmer ii
1z0 804 exam-java se 7 programmer ii1z0 804 exam-java se 7 programmer ii
1z0 804 exam-java se 7 programmer ii
 
C++ Language
C++ LanguageC++ Language
C++ Language
 

More from maxinesmith73660

You have been chosen to present in front of your local governing boa.docx
You have been chosen to present in front of your local governing boa.docxYou have been chosen to present in front of your local governing boa.docx
You have been chosen to present in front of your local governing boa.docxmaxinesmith73660
 
You have been charged with overseeing the implementation of cybersec.docx
You have been charged with overseeing the implementation of cybersec.docxYou have been charged with overseeing the implementation of cybersec.docx
You have been charged with overseeing the implementation of cybersec.docxmaxinesmith73660
 
You have been commissioned to create a manual covering the installat.docx
You have been commissioned to create a manual covering the installat.docxYou have been commissioned to create a manual covering the installat.docx
You have been commissioned to create a manual covering the installat.docxmaxinesmith73660
 
You have been challenged by a mentor you respect and admire to demon.docx
You have been challenged by a mentor you respect and admire to demon.docxYou have been challenged by a mentor you respect and admire to demon.docx
You have been challenged by a mentor you respect and admire to demon.docxmaxinesmith73660
 
You have been chosen as the consultant group to assess the organizat.docx
You have been chosen as the consultant group to assess the organizat.docxYou have been chosen as the consultant group to assess the organizat.docx
You have been chosen as the consultant group to assess the organizat.docxmaxinesmith73660
 
You have been assigned a reading by WMF Petrie; Diospolis Parva (.docx
You have been assigned a reading by WMF Petrie; Diospolis Parva (.docxYou have been assigned a reading by WMF Petrie; Diospolis Parva (.docx
You have been assigned a reading by WMF Petrie; Diospolis Parva (.docxmaxinesmith73660
 
You have been asked to speak to city, municipal, and state elected a.docx
You have been asked to speak to city, municipal, and state elected a.docxYou have been asked to speak to city, municipal, and state elected a.docx
You have been asked to speak to city, municipal, and state elected a.docxmaxinesmith73660
 
You have been asked to provide a presentation, covering the history .docx
You have been asked to provide a presentation, covering the history .docxYou have been asked to provide a presentation, covering the history .docx
You have been asked to provide a presentation, covering the history .docxmaxinesmith73660
 
You have been asked to organize a community health fair at a loc.docx
You have been asked to organize a community health fair at a loc.docxYou have been asked to organize a community health fair at a loc.docx
You have been asked to organize a community health fair at a loc.docxmaxinesmith73660
 
You have been asked to explain the differences between certain categ.docx
You have been asked to explain the differences between certain categ.docxYou have been asked to explain the differences between certain categ.docx
You have been asked to explain the differences between certain categ.docxmaxinesmith73660
 
You have been asked to evaluate a 3-year-old child in your clinic.  .docx
You have been asked to evaluate a 3-year-old child in your clinic.  .docxYou have been asked to evaluate a 3-year-old child in your clinic.  .docx
You have been asked to evaluate a 3-year-old child in your clinic.  .docxmaxinesmith73660
 
You have been asked to develop UML diagrams to graphically depict .docx
You have been asked to develop UML diagrams to graphically depict .docxYou have been asked to develop UML diagrams to graphically depict .docx
You have been asked to develop UML diagrams to graphically depict .docxmaxinesmith73660
 
You have been asked to develop UML diagrams to graphically depict an.docx
You have been asked to develop UML diagrams to graphically depict an.docxYou have been asked to develop UML diagrams to graphically depict an.docx
You have been asked to develop UML diagrams to graphically depict an.docxmaxinesmith73660
 
You have been asked to develop a quality improvement (QI) process fo.docx
You have been asked to develop a quality improvement (QI) process fo.docxYou have been asked to develop a quality improvement (QI) process fo.docx
You have been asked to develop a quality improvement (QI) process fo.docxmaxinesmith73660
 
You have been asked to design and deliver a Microsoft PowerPoint pre.docx
You have been asked to design and deliver a Microsoft PowerPoint pre.docxYou have been asked to design and deliver a Microsoft PowerPoint pre.docx
You have been asked to design and deliver a Microsoft PowerPoint pre.docxmaxinesmith73660
 
You have been asked to be the project manager for the development of.docx
You have been asked to be the project manager for the development of.docxYou have been asked to be the project manager for the development of.docx
You have been asked to be the project manager for the development of.docxmaxinesmith73660
 
You have been asked to conduct research on a past forensic case to a.docx
You have been asked to conduct research on a past forensic case to a.docxYou have been asked to conduct research on a past forensic case to a.docx
You have been asked to conduct research on a past forensic case to a.docxmaxinesmith73660
 
You have been asked for the summary to include the following compone.docx
You have been asked for the summary to include the following compone.docxYou have been asked for the summary to include the following compone.docx
You have been asked for the summary to include the following compone.docxmaxinesmith73660
 
You have been asked to be the project manager for the developmen.docx
You have been asked to be the project manager for the developmen.docxYou have been asked to be the project manager for the developmen.docx
You have been asked to be the project manager for the developmen.docxmaxinesmith73660
 
You have been asked by management, as a senior member of your co.docx
You have been asked by management, as a senior member of your co.docxYou have been asked by management, as a senior member of your co.docx
You have been asked by management, as a senior member of your co.docxmaxinesmith73660
 

More from maxinesmith73660 (20)

You have been chosen to present in front of your local governing boa.docx
You have been chosen to present in front of your local governing boa.docxYou have been chosen to present in front of your local governing boa.docx
You have been chosen to present in front of your local governing boa.docx
 
You have been charged with overseeing the implementation of cybersec.docx
You have been charged with overseeing the implementation of cybersec.docxYou have been charged with overseeing the implementation of cybersec.docx
You have been charged with overseeing the implementation of cybersec.docx
 
You have been commissioned to create a manual covering the installat.docx
You have been commissioned to create a manual covering the installat.docxYou have been commissioned to create a manual covering the installat.docx
You have been commissioned to create a manual covering the installat.docx
 
You have been challenged by a mentor you respect and admire to demon.docx
You have been challenged by a mentor you respect and admire to demon.docxYou have been challenged by a mentor you respect and admire to demon.docx
You have been challenged by a mentor you respect and admire to demon.docx
 
You have been chosen as the consultant group to assess the organizat.docx
You have been chosen as the consultant group to assess the organizat.docxYou have been chosen as the consultant group to assess the organizat.docx
You have been chosen as the consultant group to assess the organizat.docx
 
You have been assigned a reading by WMF Petrie; Diospolis Parva (.docx
You have been assigned a reading by WMF Petrie; Diospolis Parva (.docxYou have been assigned a reading by WMF Petrie; Diospolis Parva (.docx
You have been assigned a reading by WMF Petrie; Diospolis Parva (.docx
 
You have been asked to speak to city, municipal, and state elected a.docx
You have been asked to speak to city, municipal, and state elected a.docxYou have been asked to speak to city, municipal, and state elected a.docx
You have been asked to speak to city, municipal, and state elected a.docx
 
You have been asked to provide a presentation, covering the history .docx
You have been asked to provide a presentation, covering the history .docxYou have been asked to provide a presentation, covering the history .docx
You have been asked to provide a presentation, covering the history .docx
 
You have been asked to organize a community health fair at a loc.docx
You have been asked to organize a community health fair at a loc.docxYou have been asked to organize a community health fair at a loc.docx
You have been asked to organize a community health fair at a loc.docx
 
You have been asked to explain the differences between certain categ.docx
You have been asked to explain the differences between certain categ.docxYou have been asked to explain the differences between certain categ.docx
You have been asked to explain the differences between certain categ.docx
 
You have been asked to evaluate a 3-year-old child in your clinic.  .docx
You have been asked to evaluate a 3-year-old child in your clinic.  .docxYou have been asked to evaluate a 3-year-old child in your clinic.  .docx
You have been asked to evaluate a 3-year-old child in your clinic.  .docx
 
You have been asked to develop UML diagrams to graphically depict .docx
You have been asked to develop UML diagrams to graphically depict .docxYou have been asked to develop UML diagrams to graphically depict .docx
You have been asked to develop UML diagrams to graphically depict .docx
 
You have been asked to develop UML diagrams to graphically depict an.docx
You have been asked to develop UML diagrams to graphically depict an.docxYou have been asked to develop UML diagrams to graphically depict an.docx
You have been asked to develop UML diagrams to graphically depict an.docx
 
You have been asked to develop a quality improvement (QI) process fo.docx
You have been asked to develop a quality improvement (QI) process fo.docxYou have been asked to develop a quality improvement (QI) process fo.docx
You have been asked to develop a quality improvement (QI) process fo.docx
 
You have been asked to design and deliver a Microsoft PowerPoint pre.docx
You have been asked to design and deliver a Microsoft PowerPoint pre.docxYou have been asked to design and deliver a Microsoft PowerPoint pre.docx
You have been asked to design and deliver a Microsoft PowerPoint pre.docx
 
You have been asked to be the project manager for the development of.docx
You have been asked to be the project manager for the development of.docxYou have been asked to be the project manager for the development of.docx
You have been asked to be the project manager for the development of.docx
 
You have been asked to conduct research on a past forensic case to a.docx
You have been asked to conduct research on a past forensic case to a.docxYou have been asked to conduct research on a past forensic case to a.docx
You have been asked to conduct research on a past forensic case to a.docx
 
You have been asked for the summary to include the following compone.docx
You have been asked for the summary to include the following compone.docxYou have been asked for the summary to include the following compone.docx
You have been asked for the summary to include the following compone.docx
 
You have been asked to be the project manager for the developmen.docx
You have been asked to be the project manager for the developmen.docxYou have been asked to be the project manager for the developmen.docx
You have been asked to be the project manager for the developmen.docx
 
You have been asked by management, as a senior member of your co.docx
You have been asked by management, as a senior member of your co.docxYou have been asked by management, as a senior member of your co.docx
You have been asked by management, as a senior member of your co.docx
 

Recently uploaded

How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxCeline George
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17Celine George
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxAreebaZafar22
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxmarlenawright1
 
Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Association for Project Management
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and ModificationsMJDuyan
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfSherif Taha
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...Poonam Aher Patil
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfDr Vijay Vishwakarma
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxVishalSingh1417
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...Nguyen Thanh Tu Collection
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - Englishneillewis46
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structuredhanjurrannsibayan2
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptxMaritesTamaniVerdade
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsMebane Rash
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.pptRamjanShidvankar
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxEsquimalt MFRC
 
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxSKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxAmanpreet Kaur
 

Recently uploaded (20)

Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptx
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
 
Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdf
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structure
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxSKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
 

Consider this code using the ArrayBag of Section 5.2 and the Locat.docx

  • 1. Consider this code using the ArrayBag of Section 5.2 and the Location class from Chapter 2. What is the output? Location i = new Location(0, 3); Location j = new Location(0, 3); b.add(i); b.add(j); System.out.println(b.countOccurrences(i)); A. 0 B. 1 C. 2 D. 3 Suppose that b and c are Integer objects. A typical use of the clone method looks like this: b = (Integer) c.clone( ); Write a short clear explanation of why the (Integer) type cast is required in this typical example. A. obj = s; B. s = obj; C. s = (String) obj; D. Two or more answers are correct.
  • 2. Suppose that obj is an Object variable and s is a String variable. Which of the following statements is a correctly-compiling widening conversion? Don't worry about possible run-time exceptions A. obj = s; B. s = obj; C. s = (String) obj; D. Two or more answers are correct. Suppose that x and y are reference variables and a program activates x.equals(y). What occurs if x is the null reference? A. A NullPointerException occurs B. It always returns true.
  • 3. C. It always returns false. D. It returns true if y is also a null reference; otherwise it returns false. Consider the implementation of the Stack using a partially- filled array. What goes wrong if we try to store the top of the Stack at location [0] and the bottom of the Stack at the last used position of the array? A. Both peek and pop would require linear time. B. Both push and pop would require linear time. C. The Stack could not be used to check balanced parentheses. D. The Stack could not be used to evaluate postfix expressions. Write some lines of code that declares an Integer object, using the Integer wrapper class. Assign the value 42 to this object, then copy this value from the Integer object to an ordinary int variable.
  • 4. Consider the usual algorithm for determining whether a sequence of parentheses is balanced. What is the maximum number of parentheses that will appear on the stack AT ANY ONE TIME when the algorithm analyzes: (()(())(()))? A. 1 B. 2 C. 3 D. 4 E. 5 or more Consider the usual algorithm to convert an infix expression to a postfix expression. Suppose that you have read 10 input characters during a conversion and that the stack now contains the symbols as shown below. Suppose that you read and process the 11th symbol of the input. What symbol is at the top of the stack in the case where the 11th symbol is each of the choices shown?
  • 5. Which of the following stack operations could result in stack underflow? Answer A. is_empty B. pop C. push D. Two or more of the above answers What is the value of the postfix expression 6 3 2 4 + - *: Answer A. Something between -15 and -100 B. Something between -5 and -15 C. Something between 5 and -5 D. Something between 5 and 15 E. Something between 15 and 100 1. An array of queues can be used to implement a priority queue, with each possible priority corresponding to its own element in the array. When is this implementation not feasible? Answer
  • 6. A. When the number of possible priorities is huge. B. When the number of possible priorities is small. C. When the queues are implemented using a linked list. D. When the queues are implemented with circular arrays. Consider the implementation of the Queue using a circular array. What goes wrong if we try to keep all the items at the front of a partially-filled array (so that data[0] is always the front). Answer A. The constructor would require linear time. B. The getFront method would require linear time.
  • 7. C. The insert method would require linear time. D. The isEmpty method would require linear time. If data is a circular array of CAPACITY elements, and rear is an index into that array, what is the formula for the index after rear? Answer A. (rear % 1) + CAPACITY B. rear % (1 + CAPACITY) C. (rear + 1) % CAPACITY D. rear + (1 % CAPACITY) In the linked-list version of the Queue class, which operations require linear time for their worst-case behavior? Answer A. getFront
  • 8. B. insert C. isEmpty D. None of these operations require linear time. Which of the following expressions evaluates to true with approximate probability equal to P? (P is double and 0 <= P <= 1). Answer A. Math.random() < P B. Math.random() > P C. Math.random() < P * 100 D. Math.random() > P * 100 Consider the following method: public static void test_a(int n) { System.out.println(n + " "); if (n>0) test_a(n-2); }
  • 9. What is printed by the call test_a(4)? A. 0 2 4 B. 0 2 C. 2 4 D. 4 2 E. 4 2 0 Consider the following method: public static boolean deadend() // Postcondition: The return value is true if the direction directly // in front is a dead end (i.e., a direction that cannot contain the // tapestry). { return inquire("Are you facing a wall?") || inquire("Is your name written in front of you?"); } Explain why the method deadend sometimes asks 2 questions and sometimes asks only 1. Consider the following method: void superWriteVertical(int number) // Postcondition: The digits of the number have been written, // stacked vertically. If number is negative, then a negative
  • 10. // sign appears on top. { if (number < 0) { System.out.println("-"); superWriteVertical(-number); } else if (number < 10) System.out.println(number); else { superWriteVertical(number / 10); System.out.println(number % 10); } } What values of number are directly handled by the stopping case? Suppose you are exploring a rectangular maze containing 10 rows and 20 columns. What is the maximum depth of recursion that can result if you start at the entrance and call traverse_maze? What property of fractals lends itself to recursive thinking? When the compiler compiles your program, how is a recursive
  • 11. call treated differently than a non-recursive method call? For this project, write a program that stores integers in a binary search tree. The tree should use the BTNode class which is provided. Write a test program that generates 20 random numbers in the range of -50 to 50 to build the tree and then uses preorderPrint, inorderPrint, and postOrderPrint to display the contents of the tree. To get an A implement a new method for the BTNode class which creates a Java vector class to contain the data from all the nodes in the tree. The specification for this method is provided in the BTNode file. Details about the Java vector class are provided in Appendix D, although the only vector method you'll use is addElement. Also specify and implement in-order and post-order traversals and answer the question which of the three new methods creates a vector with the entries sorted from smallest to largest? Your test program should display the vectors created by your new methods rather than the print methods of BTNode.
  • 12. // File: BTNode.java from the package edu.colorado.nodes // Complete documentation is available from the BTNode link in: // http://www.cs.colorado.edu/~main/docs/ package BTNode; import java.util.Vector; /**************************************************** ************************** * A <CODE>BTNode&lt;<E&gt;</CODE> provides a node for a binary tree. Each node * contains a piece of data (which is a reference to an E object) and references * to a left and right child. The references to children may be null to indicate * that there is no child. The reference stored in a node can also be null. * * <dl><dt><b>Limitations:</b> <dd>
  • 13. * Beyond <CODE>Int.MAX_VALUE</CODE> elements, <CODE>treeSize</CODE>, is * wrong. * * <dt><b>Java Source Code for this class:</b><dd> * <A HREF="../../../../edu/colorado/nodes/BTNode.java"> * http://www.cs.colorado.edu/~main/edu/colorado/nodes/BTNode. java </A> * * @author Michael Main * <A HREF="mailto:[email protected]"> ([email protected]) </A> * * @version * Jul 22, 2005 ***************************************************** *************************/ public class BTNode<E> {
  • 14. // Invariant of the BTNode<E> class: // 1. Each node has one reference to an E Object, stored in the instance // variable data. // 2. The instance variables left and right are references to the node's // left and right children. private E data; private BTNode<E> left, right; /** * Initialize a <CODE>BTNode</CODE> with a specified initial data and links * children. Note that a child link may be the null reference, * which indicates that the new node does not have that child. * @param <CODE>initialData</CODE> * the initial data of this new node * @param <CODE>initialLeft</CODE> * a reference to the left child of this new node--this reference may be null
  • 15. * to indicate that there is no node after this new node. * @param <CODE>initialRight</CODE> * a reference to the right child of this new node--this reference may be null * to indicate that there is no node after this new node. * <dt><b>Postcondition:</b><dd> * This node contains the specified data and links to its children. **/ public BTNode(E initialData, BTNode<E> initialLeft, BTNode<E> initialRight) { data = initialData; left = initialLeft; right = initialRight; } /** * Accessor method to get the data from this node.
  • 16. * @param - none * @return * the data from this node **/ public E getData( ) { return data; } /** * Accessor method to get a reference to the left child of this node. * @param - none * @return * a reference to the left child of this node (or the null reference if there * is no left child) **/
  • 17. public BTNode<E> getLeft( ) { return left; } /** * Accessor method to get the data from the leftmost node of the tree below * this node. * @param - none * @return * the data from the deepest node that can be reached from this node by * following left links. **/ public E getLeftmostData( ) { if (left == null)
  • 18. return data; else return left.getLeftmostData( ); } /** * Accessor method to get a reference to the right child of this node. * @param - none * @return * a reference to the right child of this node (or the null reference if there * is no right child) **/ public BTNode<E> getRight( ) { return right; }
  • 19. /** * Accessor method to get the data from the rightmost node of the tree below * this node. * @param - none * @return * the data from the deepest node that can be reached from this node by * following right links. **/ public E getRightmostData( ) { if (left == null) return data; else return left.getRightmostData( ); }
  • 20. /** * Uses an inorder traversal to print the data from each node at or below * this node of the binary tree. * @param - none * <dt><b>Postcondition:</b><dd> * The data of this node and all its descendants have been writeen by * <CODE>System.out.println( )</CODE> using an inorder traversal. **/ public void inorderPrint( ) { if (left != null) left.inorderPrint( ); System.out.println(data); if (right != null)
  • 21. right.inorderPrint( ); } /** * Accessor method to determine whether a node is a leaf. * @param - none * @return * <CODE>true</CODE> (if this node is a leaf) or * <CODE>false</CODE> (if this node is not a leaf. **/ public boolean isLeaf( ) { return (left == null) && (right == null); } /**
  • 22. * Uses a preorder traversal to print the data from each node at or below * this node of the binary tree. * @param - none * <dt><b>Postcondition:</b><dd> * The data of this node and all its descendants have been writeen by * <CODE>System.out.println( )</CODE> using a preorder traversal. **/ public void preorderPrint( ) { System.out.println(data); if (left != null) left.preorderPrint( ); if (right != null) right.preorderPrint( ); }
  • 23. /** * Uses a postorder traversal to print the data from each node at or below * this node of the binary tree. * @param - none * <dt><b>Postcondition:</b><dd> * The data of this node and all its descendants have been writeen by * <CODE>System.out.println( )</CODE> using a postorder traversal. **/ public void postorderPrint( ) { if (left != null) left.postorderPrint( ); if (right != null) right.postorderPrint( ); System.out.println(data); }
  • 24. /** * Uses an inorder traversal to print the data from each node at or below * this node of the binary tree, with indentations to indicate the depth * of each node. * @param <CODE>depth</CODE> * the depth of this node (with 0 for root, 1 for the root's * children, and so on)( * <dt><b>Precondition:</b><dd> * <CODE>depth</CODE> is the depth of this node. * <dt><b>Postcondition:</b><dd> * The data of this node and all its descendants have been writeen by * <CODE>System.out.println( )</CODE> using an inorder traversal. * The indentation of each line of data is four times its depth in the * tree. A dash "--" is printed at any place where a child has
  • 25. no * sibling. **/ public void print(int depth) { int i; // Print the indentation and the data from the current node: for (i = 1; i <= depth; i++) System.out.print(" "); System.out.println(data); // Print the left subtree (or a dash if there is a right child and no left child) if (left != null) left.print(depth+1); else if (right != null) { for (i = 1; i <= depth+1; i++)
  • 26. System.out.print(" "); System.out.println("--"); } // Print the right subtree (or a dash if there is a left child and no left child) if (right != null) right.print(depth+1); else if (left != null) { for (i = 1; i <= depth+1; i++) System.out.print(" "); System.out.println("--"); } } /**
  • 27. * Remove the leftmost most node of the tree with this node as its root. * @param - none * <dt><b>Postcondition:</b><dd> * The tree starting at this node has had its leftmost node removed (i.e., * the deepest node that can be reached by following left links). The * return value is a reference to the root of the new (smaller) tree. * This return value could be null if the original tree had only one * node (since that one node has now been removed). **/ public BTNode<E> removeLeftmost( ) { if (left == null) return right; else { left = left.removeLeftmost( );
  • 28. return this; } } /** * Remove the rightmost most node of the tree with this node as its root. * @param - none * <dt><b>Postcondition:</b><dd> * The tree starting at this node has had its rightmost node removed (i.e., * the deepest node that can be reached by following right links). The * return value is a reference to the root of the new (smaller) tree. * This return value could be null if the original tree had only one * node (since that one node has now been removed). **/
  • 29. public BTNode<E> removeRightmost( ) { if (right == null) return left; else { right = right.removeRightmost( ); return this; } } /** * Modification method to set the data in this node. * @param <CODE>newData</CODE> * the new data to place in this node * <dt><b>Postcondition:</b><dd> * The data of this node has been set to <CODE>newData</CODE>. **/
  • 30. public void setData(E newData) { data = newData; } /** * Modification method to set the link to the left child of this node. * @param <CODE>newLeft</CODE> * a reference to the node that should appear as the left child of this node * (or the null reference if there is no left child for this node) * <dt><b>Postcondition:</b><dd> * The link to the left child of this node has been set to <CODE>newLeft</CODE>. * Any other node (that used to be the left child) is no longer connected to * this node. **/
  • 31. public void setLeft(BTNode<E> newLeft) { left = newLeft; } /** * Modification method to set the link to the right child of this node. * @param <CODE>newLeft</CODE> * a reference to the node that should appear as the right child of this node * (or the null reference if there is no right child for this node) * <dt><b>Postcondition:</b><dd> * The link to the right child of this node has been set to <CODE>newRight</CODE>. * Any other node (that used to be the right child) is no longer connected to * this node.
  • 32. **/ public void setRight(BTNode<E> newRight) { right = newRight; } /** * Copy a binary tree. * @param <CODE>source</CODE> * a reference to the root of a binary tree that will be copied (which may be * an empty tree where <CODE>source</CODE> is null) * @return * The method has made a copy of the binary tree starting at * <CODE>source</CODE>. The return value is a reference to the root of the copy. * @exception OutOfMemoryError * Indicates that there is insufficient memory for the new tree.
  • 33. **/ public static <E> BTNode<E> treeCopy(BTNode<E> source) { BTNode<E> leftCopy, rightCopy; if (source == null) return null; else { leftCopy = treeCopy(source.left); rightCopy = treeCopy(source.right); return new BTNode<E>(source.data, leftCopy, rightCopy); } } /**
  • 34. * Count the number of nodes in a binary tree. * @param <CODE>root</CODE> * a reference to the root of a binary tree (which may be * an empty tree where <CODE>source</CODE> is null) * @return * the number of nodes in the binary tree * <dt><b>Note:</b><dd> * A wrong answer occurs for trees larger than * <CODE>INT.MAX_VALUE</CODE>. **/ public static <E> long treeSize(BTNode<E> root) { if (root == null) return 0; else return 1 + treeSize(root.left) + treeSize(root.right); } /**
  • 35. * The method does a pre-order traversal of all nodes at or below this node, * appending the data from each node to a Vector * @param v * the Vector that will have data appended to it * @precondition * The node and all its descendants have been traversed with a pre-order * traversal, and all data has been apended to v using v.addElement * @postcondition * The node and all its descendants have been traversed with a pre-order * traversal, and all data has been appended to v using v.addElement. * @throws NullPointerException * Indicates that v is null. * */ public void preorderVector(Vector<E> v){
  • 36. } }
  • 37. // FILE: AnimalGuess.java // This animal-guessing program illustrates the use of the binary tree node class.
  • 38. import edu.colorado.nodes.BTNode; import java.util.Scanner; /**************************************************** ************************** * The <CODE>AnimalGuess</CODE> Java application illustrates the use of * the binary tree node class is a small animal-guessing game. * * <p><dt><b>Java Source Code for this class:</b><dd> * <A HREF="../applications/Animals.java"> * http://www.cs.colorado.edu/~main/applications/Animals.java * </A> * * @author Michael Main * <A HREF="mailto:[email protected]"> ([email protected]) </A> * * @version
  • 39. * Jul 22, 2005 ***************************************************** *************************/ public class AnimalGuess { private static Scanner stdin = new Scanner(System.in); /** * The main method prints instructions and repeatedly plays the * animal-guessing game. As the game is played, the taxonomy tree * grows by learning new animals. The <CODE>String</CODE> argument * (<CODE>args</CODE>) is not used in this implementation. **/ public static void main(String[ ] args) { BTNode<String> root;
  • 40. instruct( ); root = beginningTree( ); do play(root); while (query("Shall we play again?")); System.out.println("Thanks for teaching me a thing or two."); } /** * Print instructions for the animal-guessing game. **/ public static void instruct( ) { System.out.println("Please think of an animal."); System.out.println("I will ask some yes/no questions to try to figure");
  • 41. System.out.println("out what you are."); } /** * Play one round of the animal guessing game. * @param <CODE>current</CODE> * a reference to the root node of a binary taxonomy tree that will be * used to play the game. * <dt><b>Postcondition:</b><dd> * The method has played one round of the game, and possibly * added new information about a new animal. * @exception java.lang.OutOfMemoryError * Indicates that there is insufficient memory to add new * information to the tree. **/ public static void play(BTNode<String> current)
  • 42. { while (!current.isLeaf( )) { if (query(current.getData( ))) current = current.getLeft( ); else current = current.getRight( ); } System.out.print("My guess is " + current.getData( ) + ". "); if (!query("Am I right?")) learn(current); else System.out.println("I knew it all along!"); } /**
  • 43. * Construct a small taxonomy tree with four animals. * @param - none * @return * a reference to the root of a taxonomy tree with the animals: * kangaroo, mouse, trout, robin. * @exception OutOfMemoryError * Indicates that there is insufficient memory to create the tree. **/ public static BTNode<String> beginningTree( ) { BTNode<String> root; BTNode<String> child; final String ROOT_QUESTION = "Are you a mammal?"; final String LEFT_QUESTION = "Are you bigger than a cat?"; final String RIGHT_QUESTION = "Do you live underwater?";
  • 44. final String ANIMAL1 = "Kangaroo"; final String ANIMAL2 = "Mouse"; final String ANIMAL3 = "Trout"; final String ANIMAL4 = "Robin"; // Create the root node with the question “Are you a mammal?” root = new BTNode<String>(ROOT_QUESTION, null, null); // Create and attach the left subtree. child = new BTNode<String>(LEFT_QUESTION, null, null); child.setLeft(new BTNode<String>(ANIMAL1, null, null)); child.setRight(new BTNode<String>(ANIMAL2, null, null)); root.setLeft(child); // Create and attach the right subtree. child = new BTNode<String>(RIGHT_QUESTION, null,
  • 45. null); child.setLeft(new BTNode<String>(ANIMAL3, null, null)); child.setRight(new BTNode<String>(ANIMAL4, null, null)); root.setRight(child); return root; } /** * Elicits information from the user to improve a binary taxonomy tree. * @param <CODE>current</CODE> * a reference to a leaf node of a binary taxonomy tree * <dt><b>Precondition:</b><dd> * <CODE>current</CODE> is a reference to a leaf in a binary * taxonomy tree * <dt><b>Postcondition:</b><dd>
  • 46. * Information has been elicited from the user, and the tree has * been improved. * @exception OutOfMemoryError * Indicates that there is insufficient memory to add new * information to the tree. **/ public static void learn(BTNode<String> current) // Precondition: current is a reference to a leaf in a taxonomy tree. This // leaf contains a wrong guess that was just made. // Postcondition: Information has been elicited from the user, and the tree // has been improved. { String guessAnimal; // The animal that was just guessed String correctAnimal; // The animal that the user was thinking of String newQuestion; // A question to distinguish the two animals
  • 47. // Set Strings for the guessed animal, correct animal and a new question. guessAnimal = current.getData( ); System.out.println("I give up. What are you? "); correctAnimal = stdin.nextLine( ); System.out.println("Please type a yes/no question that will distinguish a"); System.out.println(correctAnimal + " from a " + guessAnimal + "."); newQuestion = stdin.nextLine( ); // Put the new question in the current node, and add two new children. current.setData(newQuestion); System.out.println("As a " + correctAnimal + ", " + newQuestion); if (query("Please answer")) { current.setLeft(new BTNode<String>(correctAnimal, null, null));
  • 48. current.setRight(new BTNode<String>(guessAnimal, null, null)); } else { current.setLeft(new BTNode<String>(guessAnimal, null, null)); current.setRight(new BTNode<String>(correctAnimal, null, null)); } } public static boolean query(String prompt) { String answer; System.out.print(prompt + " [Y or N]: "); answer = stdin.nextLine( ).toUpperCase( ); while (!answer.startsWith("Y") && !answer.startsWith("N"))
  • 49. { System.out.print("Invalid response. Please type Y or N: "); answer = stdin.nextLine( ).toUpperCase( ); } return answer.startsWith("Y"); } }
  • 50. // File: IntTreeBag.java from the package edu.colorado.collections
  • 51. // The implementation of most methods in this file is left as a student // exercise from Section 9.5 of "Data Structures and Other Objects Using Java" // Check with your instructor to see whether you should put this class in // a package. At the moment, it is declared as part of edu.colorado.collections: package edu.colorado.collections; import edu.colorado.nodes.IntBTNode; /**************************************************** ************************** * This class is a homework assignment; * An <CODE>IntTreeBag</CODE> is a collection of int numbers. * * <dl><dt><b>Limitations:</b> <dd> * Beyond <CODE>Integer.MAX_VALUE</CODE> elements, <CODE>countOccurrences</CODE>,
  • 52. * and <CODE>size</CODE> are wrong. * * <dt><b>Outline of Java Source Code for this class:</b><dd> * <A HREF="../../../../edu/colorado/collections/IntTreeBag.java"> * http://www.cs.colorado.edu/~main/edu/colorado/collections/Int TreeBag.java * </A> * * <dt><b>Note:</b><dd> * This file contains only blank implementations ("stubs") * because this is a Programming Project for my students. * * @version * Jan 24, 1999 * * @see IntArrayBag * @see IntLinkedBag
  • 53. ***************************************************** *************************/ public class IntTreeBag implements Cloneable { // Invariant of the IntTreeBag class: // 1. The elements in the bag are stored in a binary search tree. // 2. The instance variable root is a reference to the root of the // binary search tree (or null for an empty tree). private IntBTNode root; /** * Insert a new element into this bag. * @param <CODE>element</CODE> * the new element that is being inserted * <dt><b>Postcondition:</b><dd> * A new copy of the element has been added to this bag. * @exception OutOfMemoryError
  • 54. * Indicates insufficient memory a new IntBTNode. **/ public void add(int element) { // Implemented by student. } /** * Add the contents of another bag to this bag. * @param <CODE>addend</CODE> * a bag whose contents will be added to this bag * <dt><b>Precondition:</b><dd> * The parameter, <CODE>addend</CODE>, is not null. * <dt><b>Postcondition:</b><dd> * The elements from <CODE>addend</CODE> have been added to this bag. * @exception IllegalArgumentException
  • 55. * Indicates that <CODE>addend</CODE> is null. * @exception OutOfMemoryError * Indicates insufficient memory to increase the size of the bag. **/ public void addAll(IntTreeBag addend) { // Implemented by student. } /** * Generate a copy of this bag. * @param - none * @return * The return value is a copy of this bag. Subsequent changes to the * copy will not affect the original, nor vice versa. Note that the return * value must be type cast to an
  • 56. <CODE>IntTreeBag</CODE> before it can be used. * @exception OutOfMemoryError * Indicates insufficient memory for creating the clone. **/ public Object clone( ) { // Clone an IntTreeBag object. // Student will replace this return statement with their own code: return null; } /** * Accessor method to count the number of occurrences of a particular element * in this bag. * @param <CODE>target</CODE> * the element that needs to be counted * @return
  • 57. * the number of times that <CODE>target</CODE> occurs in this bag **/ public int countOccurrences(int target) { // Student will replace this return statement with their own code: return 0; } /** * Remove one copy of a specified element from this bag. * @param <CODE>target</CODE> * the element to remove from the bag * <dt><b>Postcondition:</b><dd> * If <CODE>target</CODE> was found in the bag, then one copy of * <CODE>target</CODE> has been removed and the method returns true.
  • 58. * Otherwise the bag remains unchanged and the method returns false. **/ private boolean remove(int target) { // Student will replace this return statement with their own code: return false; } /** * Determine the number of elements in this bag. * @param - none * @return * the number of elements in this bag **/ public int size( ) {
  • 59. return IntBTNode.treeSize(root); } /** * Create a new bag that contains all the elements from two other bags. * @param <CODE>b1</CODE> * the first of two bags * @param <CODE>b2</CODE> * the second of two bags * <dt><b>Precondition:</b><dd> * Neither b1 nor b2 is null. * @return * the union of b1 and b2 * @exception IllegalArgumentException * Indicates that one of the arguments is null. * @exception OutOfMemoryError * Indicates insufficient memory for the new bag.
  • 60. **/ public static IntTreeBag union(IntTreeBag b1, IntTreeBag b2) { // Student will replace this return statement with their own code: return null; } }