SlideShare a Scribd company logo
5. Design and implement a method contains 2 for BinarySearchTree, functionall equivalent to
the contains method, that does not use recursion.
show the driver code and do this in java
this is the binarysearchtree
import java.util.*; // Iterator, Comparator
public class BinarySearchTree implements BSTInterface
{
protected BSTNode root; // reference to the root of this BST
protected Comparator comp; // used for all comparisons
protected boolean found; // used by remove
public BinarySearchTree()
// Precondition: T implements Comparable
// Creates an empty BST object - uses the natural order of elements.
{
root = null;
comp = new Comparator()
{
public int compare(T element1, T element2)
{
return ((Comparable)element1).compareTo(element2);
}
};
}
public BinarySearchTree(Comparator comp)
// Creates an empty BST object - uses Comparator comp for order
// of elements.
{
root = null;
this.comp = comp;
}
public boolean isFull()
// Returns false; this link-based BST is never full.
{
return false;
}
public boolean isEmpty()
// Returns true if this BST is empty; otherwise, returns false.
{
return (root == null);
}
public T min()
// If this BST is empty, returns null;
// otherwise returns the smallest element of the tree.
{
if (isEmpty())
return null;
else
{
BSTNode node = root;
while (node.getLeft() != null)
node = node.getLeft();
return node.getInfo();
}
}
public T max()
// If this BST is empty, returns null;
// otherwise returns the largest element of the tree.
{
if (isEmpty())
return null;
else
{
BSTNode node = root;
while (node.getRight() != null)
node = node.getRight();
return node.getInfo();
}
}
private int recSize(BSTNode node)
// Returns the number of elements in subtree rooted at node.
{
if (node == null)
return 0;
else
return 1 + recSize(node.getLeft()) + recSize(node.getRight());
}
public int size()
// Returns the number of elements in this BST.
{
return recSize(root);
}
public int size2()
// Returns the number of elements in this BST.
{
int count = 0;
if (root != null)
{
LinkedStack> nodeStack = new LinkedStack>();
BSTNode currNode;
nodeStack.push(root);
while (!nodeStack.isEmpty())
{
currNode = nodeStack.top();
nodeStack.pop();
count++;
if (currNode.getLeft() != null)
nodeStack.push(currNode.getLeft());
if (currNode.getRight() != null)
nodeStack.push(currNode.getRight());
}
}
return count;
}
private boolean recContains(T target, BSTNode node)
// Returns true if the subtree rooted at node contains info i such that
// comp.compare(target, i) == 0; otherwise, returns false.
{
if (node == null)
return false; // target is not found
else if (comp.compare(target, node.getInfo()) < 0)
return recContains(target, node.getLeft()); // Search left subtree
else if (comp.compare(target, node.getInfo()) > 0)
return recContains(target, node.getRight()); // Search right subtree
else
return true; // target is found
}
public boolean contains (T target)
// Returns true if this BST contains a node with info i such that
// comp.compare(target, i) == 0; otherwise, returns false.
{
return recContains(target, root);
}
private T recGet(T target, BSTNode node)
// Returns info i from the subtree rooted at node such that
// comp.compare(target, i) == 0; if no such info exists, returns null.
{
if (node == null)
return null; // target is not found
else if (comp.compare(target, node.getInfo()) < 0)
return recGet(target, node.getLeft()); // get from left subtree
else
if (comp.compare(target, node.getInfo()) > 0)
return recGet(target, node.getRight()); // get from right subtree
else
return node.getInfo(); // target is found
}
public T get(T target)
// Returns info i from node of this BST where comp.compare(target, i) == 0;
// if no such node exists, returns null.
{
return recGet(target, root);
}
private BSTNode recAdd(T element, BSTNode node)
// Adds element to tree rooted at node; tree retains its BST property.
{
if (node == null)
// Addition place found
node = new BSTNode(element);
else if (comp.compare(element, node.getInfo()) <= 0)
node.setLeft(recAdd(element, node.getLeft())); // Add in left subtree
else
node.setRight(recAdd(element, node.getRight())); // Add in right subtree
return node;
}
public boolean add (T element)
// Adds element to this BST. The tree retains its BST property.
{
root = recAdd(element, root);
return true;
}
/*
public boolean add (T element)
// Adds element to this BST. The tree retains its BST property.
{
BSTNode newNode = new BSTNode(element);
BSTNode prev = null, curr = null;
if (root == null)
root = newNode;
else
{
curr = root;
while (curr != null)
{
if (comp.compare(element, curr.getInfo()) <= 0)
{
prev = curr;
curr = curr.getLeft();
}
else
{
prev = curr;
curr = curr.getRight();
}
}
if (comp.compare(element, prev.getInfo()) <= 0)
prev.setLeft(newNode);
else
prev.setLeft(newNode);
}
return true;
}
*/
private T getPredecessor(BSTNode subtree)
// Returns the information held in the rightmost node of subtree
{
BSTNode temp = subtree;
while (temp.getRight() != null)
temp = temp.getRight();
return temp.getInfo();
}
private BSTNode removeNode(BSTNode node)
// Removes the information at node from the tree.
{
T data;
if (node.getLeft() == null)
return node.getRight();
else if (node.getRight() == null)
return node.getLeft();
else
{
data = getPredecessor(node.getLeft());
node.setInfo(data);
node.setLeft(recRemove(data, node.getLeft()));
return node;
}
}
private BSTNode recRemove(T target, BSTNode node)
// Removes element with info i from tree rooted at node such that
// comp.compare(target, i) == 0 and returns true;
// if no such node exists, returns false.
{
if (node == null)
found = false;
else if (comp.compare(target, node.getInfo()) < 0)
node.setLeft(recRemove(target, node.getLeft()));
else if (comp.compare(target, node.getInfo()) > 0)
node.setRight(recRemove(target, node.getRight()));
else
{
node = removeNode(node);
found = true;
}
return node;
}
public boolean remove (T target)
// Removes a node with info i from tree such that comp.compare(target,i) == 0
// and returns true; if no such node exists, returns false.
{
root = recRemove(target, root);
return found;
}
public Iterator getIterator(BSTInterface.Traversal orderType)
// Creates and returns an Iterator providing a traversal of a "snapshot"
// of the current tree in the order indicated by the argument.
// Supports Preorder, Postorder, and Inorder traversal.
{
final LinkedQueue infoQueue = new LinkedQueue();
if (orderType == BSTInterface.Traversal.Preorder)
preOrder(root, infoQueue);
else
if (orderType == BSTInterface.Traversal.Inorder)
inOrder(root, infoQueue);
else
if (orderType == BSTInterface.Traversal.Postorder)
postOrder(root, infoQueue);
return new Iterator()
{
public boolean hasNext()
// Returns true if the iteration has more elements; otherwise returns false.
{
return !infoQueue.isEmpty();
}
public T next()
// Returns the next element in the iteration.
// Throws NoSuchElementException - if the iteration has no more elements
{
if (!hasNext())
throw new IndexOutOfBoundsException("illegal invocation of next " +
" in BinarySearchTree iterator.n");
return infoQueue.dequeue();
}
public void remove()
// Throws UnsupportedOperationException.
// Not supported. Removal from snapshot iteration is meaningless.
{
throw new UnsupportedOperationException("Unsupported remove attempted on "
+ "BinarySearchTree iterator.n");
}
};
}
private void preOrder(BSTNode node, LinkedQueue q)
// Enqueues the elements from the subtree rooted at node into q in preOrder.
{
if (node != null)
{
q.enqueue(node.getInfo());
preOrder(node.getLeft(), q);
preOrder(node.getRight(), q);
}
}
private void inOrder(BSTNode node, LinkedQueue q)
// Enqueues the elements from the subtree rooted at node into q in inOrder.
{
if (node != null)
{
inOrder(node.getLeft(), q);
q.enqueue(node.getInfo());
inOrder(node.getRight(), q);
}
}
private void postOrder(BSTNode node, LinkedQueue q)
// Enqueues the elements from the subtree rooted at node into q in postOrder.
{
if (node != null)
{
postOrder(node.getLeft(), q);
postOrder(node.getRight(), q);
q.enqueue(node.getInfo());
}
}
public Iterator iterator()
// InOrder is the default, "natural" order.
{
return getIterator(BSTInterface.Traversal.Inorder);
}

More Related Content

Similar to 5. Design and implement a method contains 2 for BinarySearchTree, fu.pdf

Objective Binary Search Tree traversal (2 points)Use traversal.pp.pdf
Objective Binary Search Tree traversal (2 points)Use traversal.pp.pdfObjective Binary Search Tree traversal (2 points)Use traversal.pp.pdf
Objective Binary Search Tree traversal (2 points)Use traversal.pp.pdf
sivakumar19831
 
MAINCPP include ltiostreamgt include ltstringgt u.pdf
MAINCPP include ltiostreamgt include ltstringgt u.pdfMAINCPP include ltiostreamgt include ltstringgt u.pdf
MAINCPP include ltiostreamgt include ltstringgt u.pdf
adityastores21
 
Given the following codepackage data1;import java.util.;p.pdf
Given the following codepackage data1;import java.util.;p.pdfGiven the following codepackage data1;import java.util.;p.pdf
Given the following codepackage data1;import java.util.;p.pdf
illyasraja7
 
How to do the main method for this programBinaryNode.javapublic.pdf
How to do the main method for this programBinaryNode.javapublic.pdfHow to do the main method for this programBinaryNode.javapublic.pdf
How to do the main method for this programBinaryNode.javapublic.pdf
feelingcomputors
 
In the class LinkedBinarySearchTree implement only the following metho.pdf
In the class LinkedBinarySearchTree implement only the following metho.pdfIn the class LinkedBinarySearchTree implement only the following metho.pdf
In the class LinkedBinarySearchTree implement only the following metho.pdf
sidkucheria
 
Help to implement delete_node get_succ get_pred walk and.pdf
Help to implement delete_node get_succ get_pred walk and.pdfHelp to implement delete_node get_succ get_pred walk and.pdf
Help to implement delete_node get_succ get_pred walk and.pdf
contact32
 
A)B) C++ program to create a Complete Binary tree from its Lin.pdf
A)B) C++ program to create a Complete Binary tree from its Lin.pdfA)B) C++ program to create a Complete Binary tree from its Lin.pdf
A)B) C++ program to create a Complete Binary tree from its Lin.pdf
anton291
 
Given a newly created Binary Search Tree with the following numerica.pdf
Given a newly created Binary Search Tree with the following numerica.pdfGiven a newly created Binary Search Tree with the following numerica.pdf
Given a newly created Binary Search Tree with the following numerica.pdf
hadpadrrajeshh
 
In this lab, you will be given a simple code for a min Heap, and you.pdf
In this lab, you will be given a simple code for a min Heap, and you.pdfIn this lab, you will be given a simple code for a min Heap, and you.pdf
In this lab, you will be given a simple code for a min Heap, and you.pdf
charanjit1717
 
Required to augment the authors Binary Search Tree (BST) code to .docx
Required to augment the authors Binary Search Tree (BST) code to .docxRequired to augment the authors Binary Search Tree (BST) code to .docx
Required to augment the authors Binary Search Tree (BST) code to .docx
debishakespeare
 
On the code which has a class in which I implementing a binary tree .pdf
On the code which has a class in which I implementing a binary tree .pdfOn the code which has a class in which I implementing a binary tree .pdf
On the code which has a class in which I implementing a binary tree .pdf
wasemanivytreenrco51
 
AnswerNote LinkedList.cpp is written and driver program main.cpp.pdf
AnswerNote LinkedList.cpp is written and driver program main.cpp.pdfAnswerNote LinkedList.cpp is written and driver program main.cpp.pdf
AnswerNote LinkedList.cpp is written and driver program main.cpp.pdf
anwarsadath111
 
Please write in C++ and should be able to compile and debug.Thank yo.pdf
Please write in C++ and should be able to compile and debug.Thank yo.pdfPlease write in C++ and should be able to compile and debug.Thank yo.pdf
Please write in C++ and should be able to compile and debug.Thank yo.pdf
ajaycosmeticslg
 
Given below is the completed implementation of MyLinkedList class. O.pdf
Given below is the completed implementation of MyLinkedList class. O.pdfGiven below is the completed implementation of MyLinkedList class. O.pdf
Given below is the completed implementation of MyLinkedList class. O.pdf
info430661
 
Modify this code to do an Insert function for an AVL tree, instead o.pdf
Modify this code to do an Insert function for an AVL tree, instead o.pdfModify this code to do an Insert function for an AVL tree, instead o.pdf
Modify this code to do an Insert function for an AVL tree, instead o.pdf
fathimaoptical
 
Here is the editable codeSolutionimport java.util.NoSuchEleme.pdf
Here is the editable codeSolutionimport java.util.NoSuchEleme.pdfHere is the editable codeSolutionimport java.util.NoSuchEleme.pdf
Here is the editable codeSolutionimport java.util.NoSuchEleme.pdf
arrowmobile
 
SinglyLinkedListPseudoCode.txtCLASS SinglyLinkedList se.docx
SinglyLinkedListPseudoCode.txtCLASS SinglyLinkedList    se.docxSinglyLinkedListPseudoCode.txtCLASS SinglyLinkedList    se.docx
SinglyLinkedListPseudoCode.txtCLASS SinglyLinkedList se.docx
jennifer822
 
Create a class BinarySearchTree- A class that implements the ADT binar.pdf
Create a class BinarySearchTree- A class that implements the ADT binar.pdfCreate a class BinarySearchTree- A class that implements the ADT binar.pdf
Create a class BinarySearchTree- A class that implements the ADT binar.pdf
shyamsunder1211
 
include ltiostreamgt include ltfstreamgt in.pdf
include ltiostreamgt include ltfstreamgt in.pdfinclude ltiostreamgt include ltfstreamgt in.pdf
include ltiostreamgt include ltfstreamgt in.pdf
adisainternational
 
import java.util.Iterator; import java.util.NoSuchElementException; .pdf
  import java.util.Iterator; import java.util.NoSuchElementException; .pdf  import java.util.Iterator; import java.util.NoSuchElementException; .pdf
import java.util.Iterator; import java.util.NoSuchElementException; .pdf
deepakangel
 

Similar to 5. Design and implement a method contains 2 for BinarySearchTree, fu.pdf (20)

Objective Binary Search Tree traversal (2 points)Use traversal.pp.pdf
Objective Binary Search Tree traversal (2 points)Use traversal.pp.pdfObjective Binary Search Tree traversal (2 points)Use traversal.pp.pdf
Objective Binary Search Tree traversal (2 points)Use traversal.pp.pdf
 
MAINCPP include ltiostreamgt include ltstringgt u.pdf
MAINCPP include ltiostreamgt include ltstringgt u.pdfMAINCPP include ltiostreamgt include ltstringgt u.pdf
MAINCPP include ltiostreamgt include ltstringgt u.pdf
 
Given the following codepackage data1;import java.util.;p.pdf
Given the following codepackage data1;import java.util.;p.pdfGiven the following codepackage data1;import java.util.;p.pdf
Given the following codepackage data1;import java.util.;p.pdf
 
How to do the main method for this programBinaryNode.javapublic.pdf
How to do the main method for this programBinaryNode.javapublic.pdfHow to do the main method for this programBinaryNode.javapublic.pdf
How to do the main method for this programBinaryNode.javapublic.pdf
 
In the class LinkedBinarySearchTree implement only the following metho.pdf
In the class LinkedBinarySearchTree implement only the following metho.pdfIn the class LinkedBinarySearchTree implement only the following metho.pdf
In the class LinkedBinarySearchTree implement only the following metho.pdf
 
Help to implement delete_node get_succ get_pred walk and.pdf
Help to implement delete_node get_succ get_pred walk and.pdfHelp to implement delete_node get_succ get_pred walk and.pdf
Help to implement delete_node get_succ get_pred walk and.pdf
 
A)B) C++ program to create a Complete Binary tree from its Lin.pdf
A)B) C++ program to create a Complete Binary tree from its Lin.pdfA)B) C++ program to create a Complete Binary tree from its Lin.pdf
A)B) C++ program to create a Complete Binary tree from its Lin.pdf
 
Given a newly created Binary Search Tree with the following numerica.pdf
Given a newly created Binary Search Tree with the following numerica.pdfGiven a newly created Binary Search Tree with the following numerica.pdf
Given a newly created Binary Search Tree with the following numerica.pdf
 
In this lab, you will be given a simple code for a min Heap, and you.pdf
In this lab, you will be given a simple code for a min Heap, and you.pdfIn this lab, you will be given a simple code for a min Heap, and you.pdf
In this lab, you will be given a simple code for a min Heap, and you.pdf
 
Required to augment the authors Binary Search Tree (BST) code to .docx
Required to augment the authors Binary Search Tree (BST) code to .docxRequired to augment the authors Binary Search Tree (BST) code to .docx
Required to augment the authors Binary Search Tree (BST) code to .docx
 
On the code which has a class in which I implementing a binary tree .pdf
On the code which has a class in which I implementing a binary tree .pdfOn the code which has a class in which I implementing a binary tree .pdf
On the code which has a class in which I implementing a binary tree .pdf
 
AnswerNote LinkedList.cpp is written and driver program main.cpp.pdf
AnswerNote LinkedList.cpp is written and driver program main.cpp.pdfAnswerNote LinkedList.cpp is written and driver program main.cpp.pdf
AnswerNote LinkedList.cpp is written and driver program main.cpp.pdf
 
Please write in C++ and should be able to compile and debug.Thank yo.pdf
Please write in C++ and should be able to compile and debug.Thank yo.pdfPlease write in C++ and should be able to compile and debug.Thank yo.pdf
Please write in C++ and should be able to compile and debug.Thank yo.pdf
 
Given below is the completed implementation of MyLinkedList class. O.pdf
Given below is the completed implementation of MyLinkedList class. O.pdfGiven below is the completed implementation of MyLinkedList class. O.pdf
Given below is the completed implementation of MyLinkedList class. O.pdf
 
Modify this code to do an Insert function for an AVL tree, instead o.pdf
Modify this code to do an Insert function for an AVL tree, instead o.pdfModify this code to do an Insert function for an AVL tree, instead o.pdf
Modify this code to do an Insert function for an AVL tree, instead o.pdf
 
Here is the editable codeSolutionimport java.util.NoSuchEleme.pdf
Here is the editable codeSolutionimport java.util.NoSuchEleme.pdfHere is the editable codeSolutionimport java.util.NoSuchEleme.pdf
Here is the editable codeSolutionimport java.util.NoSuchEleme.pdf
 
SinglyLinkedListPseudoCode.txtCLASS SinglyLinkedList se.docx
SinglyLinkedListPseudoCode.txtCLASS SinglyLinkedList    se.docxSinglyLinkedListPseudoCode.txtCLASS SinglyLinkedList    se.docx
SinglyLinkedListPseudoCode.txtCLASS SinglyLinkedList se.docx
 
Create a class BinarySearchTree- A class that implements the ADT binar.pdf
Create a class BinarySearchTree- A class that implements the ADT binar.pdfCreate a class BinarySearchTree- A class that implements the ADT binar.pdf
Create a class BinarySearchTree- A class that implements the ADT binar.pdf
 
include ltiostreamgt include ltfstreamgt in.pdf
include ltiostreamgt include ltfstreamgt in.pdfinclude ltiostreamgt include ltfstreamgt in.pdf
include ltiostreamgt include ltfstreamgt in.pdf
 
import java.util.Iterator; import java.util.NoSuchElementException; .pdf
  import java.util.Iterator; import java.util.NoSuchElementException; .pdf  import java.util.Iterator; import java.util.NoSuchElementException; .pdf
import java.util.Iterator; import java.util.NoSuchElementException; .pdf
 

More from rambagra74

5.27 Company H has an insurance policy for which it pays an annual.pdf
5.27 Company H has an insurance policy for which it pays an annual.pdf5.27 Company H has an insurance policy for which it pays an annual.pdf
5.27 Company H has an insurance policy for which it pays an annual.pdf
rambagra74
 
5.1.a Contrast the functions of the DNA and protein components of ch.pdf
5.1.a Contrast the functions of the DNA and protein components of ch.pdf5.1.a Contrast the functions of the DNA and protein components of ch.pdf
5.1.a Contrast the functions of the DNA and protein components of ch.pdf
rambagra74
 
5.2 Par�s a Mosc�. En su programa de estudios de verano en el extr.pdf
5.2 Par�s a Mosc�. En su programa de estudios de verano en el extr.pdf5.2 Par�s a Mosc�. En su programa de estudios de verano en el extr.pdf
5.2 Par�s a Mosc�. En su programa de estudios de verano en el extr.pdf
rambagra74
 
5. Cyanobacteria live mostly in aquatic habitats but they can also b.pdf
5. Cyanobacteria live mostly in aquatic habitats but they can also b.pdf5. Cyanobacteria live mostly in aquatic habitats but they can also b.pdf
5. Cyanobacteria live mostly in aquatic habitats but they can also b.pdf
rambagra74
 
5. The Federal Reserves organization1) There are (5712) Feder.pdf
5. The Federal Reserves organization1) There are (5712)   Feder.pdf5. The Federal Reserves organization1) There are (5712)   Feder.pdf
5. The Federal Reserves organization1) There are (5712) Feder.pdf
rambagra74
 
5. Mrs. Toguchi wants to determine if politicians tend to have highe.pdf
5. Mrs. Toguchi wants to determine if politicians tend to have highe.pdf5. Mrs. Toguchi wants to determine if politicians tend to have highe.pdf
5. Mrs. Toguchi wants to determine if politicians tend to have highe.pdf
rambagra74
 
41. a and b 41. Introductory Statistics Course Withdrawals. A univer.pdf
41. a and b 41. Introductory Statistics Course Withdrawals. A univer.pdf41. a and b 41. Introductory Statistics Course Withdrawals. A univer.pdf
41. a and b 41. Introductory Statistics Course Withdrawals. A univer.pdf
rambagra74
 
41) �La justificaci�n legal como �nico criterio �tico es adecuada de.pdf
41) �La justificaci�n legal como �nico criterio �tico es adecuada de.pdf41) �La justificaci�n legal como �nico criterio �tico es adecuada de.pdf
41) �La justificaci�n legal como �nico criterio �tico es adecuada de.pdf
rambagra74
 
40. What is the common challenge in the world of financea. It gen.pdf
40. What is the common challenge in the world of financea. It gen.pdf40. What is the common challenge in the world of financea. It gen.pdf
40. What is the common challenge in the world of financea. It gen.pdf
rambagra74
 
4.a. Calculate Target�s current ratio as of January 29, 2022 (show cur.pdf
4.a. Calculate Target�s current ratio as of January 29, 2022 (show cur.pdf4.a. Calculate Target�s current ratio as of January 29, 2022 (show cur.pdf
4.a. Calculate Target�s current ratio as of January 29, 2022 (show cur.pdf
rambagra74
 
5. Earth HistoryPaleogeography - World. Check and double-click the .pdf
5. Earth HistoryPaleogeography - World. Check and double-click the .pdf5. Earth HistoryPaleogeography - World. Check and double-click the .pdf
5. Earth HistoryPaleogeography - World. Check and double-click the .pdf
rambagra74
 
7. Para comprender mejor la prehistoria de la isla hawaiana de Lana.pdf
7. Para comprender mejor la prehistoria de la isla hawaiana de Lana.pdf7. Para comprender mejor la prehistoria de la isla hawaiana de Lana.pdf
7. Para comprender mejor la prehistoria de la isla hawaiana de Lana.pdf
rambagra74
 
7. Lawn Spray Inc. desarrolla y produce equipos de pulverizaci�n.pdf
7. Lawn Spray Inc. desarrolla y produce equipos de pulverizaci�n.pdf7. Lawn Spray Inc. desarrolla y produce equipos de pulverizaci�n.pdf
7. Lawn Spray Inc. desarrolla y produce equipos de pulverizaci�n.pdf
rambagra74
 
701 () � Kenneth_Laudon,_J... a a+ as Part One Ogriesions, Mrugemer.pdf
701 () �  Kenneth_Laudon,_J... a a+ as Part One Ogriesions, Mrugemer.pdf701 () �  Kenneth_Laudon,_J... a a+ as Part One Ogriesions, Mrugemer.pdf
701 () � Kenneth_Laudon,_J... a a+ as Part One Ogriesions, Mrugemer.pdf
rambagra74
 
71 of all students at a college still need to take another math class.pdf
71 of all students at a college still need to take another math class.pdf71 of all students at a college still need to take another math class.pdf
71 of all students at a college still need to take another math class.pdf
rambagra74
 
7.4.3 4.3 Consider a set of independent data observations x1,�.pdf
7.4.3 4.3 Consider a set of independent data observations x1,�.pdf7.4.3 4.3 Consider a set of independent data observations x1,�.pdf
7.4.3 4.3 Consider a set of independent data observations x1,�.pdf
rambagra74
 
7.16 LAB Smallest and largest numbers in a listWrite a program th.pdf
7.16 LAB Smallest and largest numbers in a listWrite a program th.pdf7.16 LAB Smallest and largest numbers in a listWrite a program th.pdf
7.16 LAB Smallest and largest numbers in a listWrite a program th.pdf
rambagra74
 
7. El balance general de Tucker Company reflejaba activos por $12,.pdf
7. El balance general de Tucker Company reflejaba activos por $12,.pdf7. El balance general de Tucker Company reflejaba activos por $12,.pdf
7. El balance general de Tucker Company reflejaba activos por $12,.pdf
rambagra74
 
4.3 Expresi�n positiva y cort�s Revise las siguientes declaracio.pdf
4.3 Expresi�n positiva y cort�s Revise las siguientes declaracio.pdf4.3 Expresi�n positiva y cort�s Revise las siguientes declaracio.pdf
4.3 Expresi�n positiva y cort�s Revise las siguientes declaracio.pdf
rambagra74
 
7. In a population of 1000 oats, there is a single Mendelian locus.pdf
7. In a population of 1000 oats, there is a single Mendelian locus.pdf7. In a population of 1000 oats, there is a single Mendelian locus.pdf
7. In a population of 1000 oats, there is a single Mendelian locus.pdf
rambagra74
 

More from rambagra74 (20)

5.27 Company H has an insurance policy for which it pays an annual.pdf
5.27 Company H has an insurance policy for which it pays an annual.pdf5.27 Company H has an insurance policy for which it pays an annual.pdf
5.27 Company H has an insurance policy for which it pays an annual.pdf
 
5.1.a Contrast the functions of the DNA and protein components of ch.pdf
5.1.a Contrast the functions of the DNA and protein components of ch.pdf5.1.a Contrast the functions of the DNA and protein components of ch.pdf
5.1.a Contrast the functions of the DNA and protein components of ch.pdf
 
5.2 Par�s a Mosc�. En su programa de estudios de verano en el extr.pdf
5.2 Par�s a Mosc�. En su programa de estudios de verano en el extr.pdf5.2 Par�s a Mosc�. En su programa de estudios de verano en el extr.pdf
5.2 Par�s a Mosc�. En su programa de estudios de verano en el extr.pdf
 
5. Cyanobacteria live mostly in aquatic habitats but they can also b.pdf
5. Cyanobacteria live mostly in aquatic habitats but they can also b.pdf5. Cyanobacteria live mostly in aquatic habitats but they can also b.pdf
5. Cyanobacteria live mostly in aquatic habitats but they can also b.pdf
 
5. The Federal Reserves organization1) There are (5712) Feder.pdf
5. The Federal Reserves organization1) There are (5712)   Feder.pdf5. The Federal Reserves organization1) There are (5712)   Feder.pdf
5. The Federal Reserves organization1) There are (5712) Feder.pdf
 
5. Mrs. Toguchi wants to determine if politicians tend to have highe.pdf
5. Mrs. Toguchi wants to determine if politicians tend to have highe.pdf5. Mrs. Toguchi wants to determine if politicians tend to have highe.pdf
5. Mrs. Toguchi wants to determine if politicians tend to have highe.pdf
 
41. a and b 41. Introductory Statistics Course Withdrawals. A univer.pdf
41. a and b 41. Introductory Statistics Course Withdrawals. A univer.pdf41. a and b 41. Introductory Statistics Course Withdrawals. A univer.pdf
41. a and b 41. Introductory Statistics Course Withdrawals. A univer.pdf
 
41) �La justificaci�n legal como �nico criterio �tico es adecuada de.pdf
41) �La justificaci�n legal como �nico criterio �tico es adecuada de.pdf41) �La justificaci�n legal como �nico criterio �tico es adecuada de.pdf
41) �La justificaci�n legal como �nico criterio �tico es adecuada de.pdf
 
40. What is the common challenge in the world of financea. It gen.pdf
40. What is the common challenge in the world of financea. It gen.pdf40. What is the common challenge in the world of financea. It gen.pdf
40. What is the common challenge in the world of financea. It gen.pdf
 
4.a. Calculate Target�s current ratio as of January 29, 2022 (show cur.pdf
4.a. Calculate Target�s current ratio as of January 29, 2022 (show cur.pdf4.a. Calculate Target�s current ratio as of January 29, 2022 (show cur.pdf
4.a. Calculate Target�s current ratio as of January 29, 2022 (show cur.pdf
 
5. Earth HistoryPaleogeography - World. Check and double-click the .pdf
5. Earth HistoryPaleogeography - World. Check and double-click the .pdf5. Earth HistoryPaleogeography - World. Check and double-click the .pdf
5. Earth HistoryPaleogeography - World. Check and double-click the .pdf
 
7. Para comprender mejor la prehistoria de la isla hawaiana de Lana.pdf
7. Para comprender mejor la prehistoria de la isla hawaiana de Lana.pdf7. Para comprender mejor la prehistoria de la isla hawaiana de Lana.pdf
7. Para comprender mejor la prehistoria de la isla hawaiana de Lana.pdf
 
7. Lawn Spray Inc. desarrolla y produce equipos de pulverizaci�n.pdf
7. Lawn Spray Inc. desarrolla y produce equipos de pulverizaci�n.pdf7. Lawn Spray Inc. desarrolla y produce equipos de pulverizaci�n.pdf
7. Lawn Spray Inc. desarrolla y produce equipos de pulverizaci�n.pdf
 
701 () � Kenneth_Laudon,_J... a a+ as Part One Ogriesions, Mrugemer.pdf
701 () �  Kenneth_Laudon,_J... a a+ as Part One Ogriesions, Mrugemer.pdf701 () �  Kenneth_Laudon,_J... a a+ as Part One Ogriesions, Mrugemer.pdf
701 () � Kenneth_Laudon,_J... a a+ as Part One Ogriesions, Mrugemer.pdf
 
71 of all students at a college still need to take another math class.pdf
71 of all students at a college still need to take another math class.pdf71 of all students at a college still need to take another math class.pdf
71 of all students at a college still need to take another math class.pdf
 
7.4.3 4.3 Consider a set of independent data observations x1,�.pdf
7.4.3 4.3 Consider a set of independent data observations x1,�.pdf7.4.3 4.3 Consider a set of independent data observations x1,�.pdf
7.4.3 4.3 Consider a set of independent data observations x1,�.pdf
 
7.16 LAB Smallest and largest numbers in a listWrite a program th.pdf
7.16 LAB Smallest and largest numbers in a listWrite a program th.pdf7.16 LAB Smallest and largest numbers in a listWrite a program th.pdf
7.16 LAB Smallest and largest numbers in a listWrite a program th.pdf
 
7. El balance general de Tucker Company reflejaba activos por $12,.pdf
7. El balance general de Tucker Company reflejaba activos por $12,.pdf7. El balance general de Tucker Company reflejaba activos por $12,.pdf
7. El balance general de Tucker Company reflejaba activos por $12,.pdf
 
4.3 Expresi�n positiva y cort�s Revise las siguientes declaracio.pdf
4.3 Expresi�n positiva y cort�s Revise las siguientes declaracio.pdf4.3 Expresi�n positiva y cort�s Revise las siguientes declaracio.pdf
4.3 Expresi�n positiva y cort�s Revise las siguientes declaracio.pdf
 
7. In a population of 1000 oats, there is a single Mendelian locus.pdf
7. In a population of 1000 oats, there is a single Mendelian locus.pdf7. In a population of 1000 oats, there is a single Mendelian locus.pdf
7. In a population of 1000 oats, there is a single Mendelian locus.pdf
 

Recently uploaded

Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
MysoreMuleSoftMeetup
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Thiyagu K
 
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
Nguyen Thanh Tu Collection
 
The Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdfThe Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdf
kaushalkr1407
 
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptxStudents, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
EduSkills OECD
 
Supporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptxSupporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptx
Jisc
 
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
BhavyaRajput3
 
Polish students' mobility in the Czech Republic
Polish students' mobility in the Czech RepublicPolish students' mobility in the Czech Republic
Polish students' mobility in the Czech Republic
Anna Sz.
 
Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptx
Pavel ( NSTU)
 
Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345
beazzy04
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
Mohd Adib Abd Muin, Senior Lecturer at Universiti Utara Malaysia
 
Sectors of the Indian Economy - Class 10 Study Notes pdf
Sectors of the Indian Economy - Class 10 Study Notes pdfSectors of the Indian Economy - Class 10 Study Notes pdf
Sectors of the Indian Economy - Class 10 Study Notes pdf
Vivekanand Anglo Vedic Academy
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
TechSoup
 
How to Break the cycle of negative Thoughts
How to Break the cycle of negative ThoughtsHow to Break the cycle of negative Thoughts
How to Break the cycle of negative Thoughts
Col Mukteshwar Prasad
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
Vivekanand Anglo Vedic Academy
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
DeeptiGupta154
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
Balvir Singh
 
1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx
JosvitaDsouza2
 
special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
Special education needs
 
Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
Jheel Barad
 

Recently uploaded (20)

Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
 
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
 
The Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdfThe Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdf
 
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptxStudents, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
 
Supporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptxSupporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptx
 
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
 
Polish students' mobility in the Czech Republic
Polish students' mobility in the Czech RepublicPolish students' mobility in the Czech Republic
Polish students' mobility in the Czech Republic
 
Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptx
 
Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
 
Sectors of the Indian Economy - Class 10 Study Notes pdf
Sectors of the Indian Economy - Class 10 Study Notes pdfSectors of the Indian Economy - Class 10 Study Notes pdf
Sectors of the Indian Economy - Class 10 Study Notes pdf
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
 
How to Break the cycle of negative Thoughts
How to Break the cycle of negative ThoughtsHow to Break the cycle of negative Thoughts
How to Break the cycle of negative Thoughts
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
 
1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx
 
special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
 
Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
 

5. Design and implement a method contains 2 for BinarySearchTree, fu.pdf

  • 1. 5. Design and implement a method contains 2 for BinarySearchTree, functionall equivalent to the contains method, that does not use recursion. show the driver code and do this in java this is the binarysearchtree import java.util.*; // Iterator, Comparator public class BinarySearchTree implements BSTInterface { protected BSTNode root; // reference to the root of this BST protected Comparator comp; // used for all comparisons protected boolean found; // used by remove public BinarySearchTree() // Precondition: T implements Comparable // Creates an empty BST object - uses the natural order of elements. { root = null; comp = new Comparator() { public int compare(T element1, T element2) { return ((Comparable)element1).compareTo(element2); } }; } public BinarySearchTree(Comparator comp) // Creates an empty BST object - uses Comparator comp for order // of elements. { root = null; this.comp = comp; } public boolean isFull()
  • 2. // Returns false; this link-based BST is never full. { return false; } public boolean isEmpty() // Returns true if this BST is empty; otherwise, returns false. { return (root == null); } public T min() // If this BST is empty, returns null; // otherwise returns the smallest element of the tree. { if (isEmpty()) return null; else { BSTNode node = root; while (node.getLeft() != null) node = node.getLeft(); return node.getInfo(); } } public T max() // If this BST is empty, returns null; // otherwise returns the largest element of the tree. { if (isEmpty()) return null; else { BSTNode node = root; while (node.getRight() != null) node = node.getRight(); return node.getInfo(); }
  • 3. } private int recSize(BSTNode node) // Returns the number of elements in subtree rooted at node. { if (node == null) return 0; else return 1 + recSize(node.getLeft()) + recSize(node.getRight()); } public int size() // Returns the number of elements in this BST. { return recSize(root); } public int size2() // Returns the number of elements in this BST. { int count = 0; if (root != null) { LinkedStack> nodeStack = new LinkedStack>(); BSTNode currNode; nodeStack.push(root); while (!nodeStack.isEmpty()) { currNode = nodeStack.top(); nodeStack.pop(); count++; if (currNode.getLeft() != null) nodeStack.push(currNode.getLeft()); if (currNode.getRight() != null) nodeStack.push(currNode.getRight()); } } return count; }
  • 4. private boolean recContains(T target, BSTNode node) // Returns true if the subtree rooted at node contains info i such that // comp.compare(target, i) == 0; otherwise, returns false. { if (node == null) return false; // target is not found else if (comp.compare(target, node.getInfo()) < 0) return recContains(target, node.getLeft()); // Search left subtree else if (comp.compare(target, node.getInfo()) > 0) return recContains(target, node.getRight()); // Search right subtree else return true; // target is found } public boolean contains (T target) // Returns true if this BST contains a node with info i such that // comp.compare(target, i) == 0; otherwise, returns false. { return recContains(target, root); } private T recGet(T target, BSTNode node) // Returns info i from the subtree rooted at node such that // comp.compare(target, i) == 0; if no such info exists, returns null. { if (node == null) return null; // target is not found else if (comp.compare(target, node.getInfo()) < 0) return recGet(target, node.getLeft()); // get from left subtree else if (comp.compare(target, node.getInfo()) > 0) return recGet(target, node.getRight()); // get from right subtree else return node.getInfo(); // target is found } public T get(T target) // Returns info i from node of this BST where comp.compare(target, i) == 0;
  • 5. // if no such node exists, returns null. { return recGet(target, root); } private BSTNode recAdd(T element, BSTNode node) // Adds element to tree rooted at node; tree retains its BST property. { if (node == null) // Addition place found node = new BSTNode(element); else if (comp.compare(element, node.getInfo()) <= 0) node.setLeft(recAdd(element, node.getLeft())); // Add in left subtree else node.setRight(recAdd(element, node.getRight())); // Add in right subtree return node; } public boolean add (T element) // Adds element to this BST. The tree retains its BST property. { root = recAdd(element, root); return true; } /* public boolean add (T element) // Adds element to this BST. The tree retains its BST property. { BSTNode newNode = new BSTNode(element); BSTNode prev = null, curr = null; if (root == null) root = newNode; else { curr = root; while (curr != null) {
  • 6. if (comp.compare(element, curr.getInfo()) <= 0) { prev = curr; curr = curr.getLeft(); } else { prev = curr; curr = curr.getRight(); } } if (comp.compare(element, prev.getInfo()) <= 0) prev.setLeft(newNode); else prev.setLeft(newNode); } return true; } */ private T getPredecessor(BSTNode subtree) // Returns the information held in the rightmost node of subtree { BSTNode temp = subtree; while (temp.getRight() != null) temp = temp.getRight(); return temp.getInfo(); } private BSTNode removeNode(BSTNode node) // Removes the information at node from the tree. { T data; if (node.getLeft() == null) return node.getRight(); else if (node.getRight() == null) return node.getLeft(); else
  • 7. { data = getPredecessor(node.getLeft()); node.setInfo(data); node.setLeft(recRemove(data, node.getLeft())); return node; } } private BSTNode recRemove(T target, BSTNode node) // Removes element with info i from tree rooted at node such that // comp.compare(target, i) == 0 and returns true; // if no such node exists, returns false. { if (node == null) found = false; else if (comp.compare(target, node.getInfo()) < 0) node.setLeft(recRemove(target, node.getLeft())); else if (comp.compare(target, node.getInfo()) > 0) node.setRight(recRemove(target, node.getRight())); else { node = removeNode(node); found = true; } return node; } public boolean remove (T target) // Removes a node with info i from tree such that comp.compare(target,i) == 0 // and returns true; if no such node exists, returns false. { root = recRemove(target, root); return found; } public Iterator getIterator(BSTInterface.Traversal orderType) // Creates and returns an Iterator providing a traversal of a "snapshot" // of the current tree in the order indicated by the argument. // Supports Preorder, Postorder, and Inorder traversal.
  • 8. { final LinkedQueue infoQueue = new LinkedQueue(); if (orderType == BSTInterface.Traversal.Preorder) preOrder(root, infoQueue); else if (orderType == BSTInterface.Traversal.Inorder) inOrder(root, infoQueue); else if (orderType == BSTInterface.Traversal.Postorder) postOrder(root, infoQueue); return new Iterator() { public boolean hasNext() // Returns true if the iteration has more elements; otherwise returns false. { return !infoQueue.isEmpty(); } public T next() // Returns the next element in the iteration. // Throws NoSuchElementException - if the iteration has no more elements { if (!hasNext()) throw new IndexOutOfBoundsException("illegal invocation of next " + " in BinarySearchTree iterator.n"); return infoQueue.dequeue(); } public void remove() // Throws UnsupportedOperationException. // Not supported. Removal from snapshot iteration is meaningless. { throw new UnsupportedOperationException("Unsupported remove attempted on " + "BinarySearchTree iterator.n"); } }; }
  • 9. private void preOrder(BSTNode node, LinkedQueue q) // Enqueues the elements from the subtree rooted at node into q in preOrder. { if (node != null) { q.enqueue(node.getInfo()); preOrder(node.getLeft(), q); preOrder(node.getRight(), q); } } private void inOrder(BSTNode node, LinkedQueue q) // Enqueues the elements from the subtree rooted at node into q in inOrder. { if (node != null) { inOrder(node.getLeft(), q); q.enqueue(node.getInfo()); inOrder(node.getRight(), q); } } private void postOrder(BSTNode node, LinkedQueue q) // Enqueues the elements from the subtree rooted at node into q in postOrder. { if (node != null) { postOrder(node.getLeft(), q); postOrder(node.getRight(), q); q.enqueue(node.getInfo()); } } public Iterator iterator() // InOrder is the default, "natural" order. { return getIterator(BSTInterface.Traversal.Inorder); }