Develop Tree.java to read the text description of trees and construct a tree. Yo
ID: 3791024 • Letter: D
Question
Develop Tree.java to read the text description of trees and construct a tree. Your class Tree should provide implement the Iterable interface. The iterable interface requires that the class return an Iterator object of a class that implements the Iterator interface:
Interface Iterator {
boolean hasNext ();
void remove() E next();
} The Iterator will return elements on the Tree using a PREORDER traversal.
Your program should perform error checking. That is, it should print an error message and exit if the tree specification is incorrect. or any of the subtrees specification is bad.
Main.java for test
Explanation / Answer
public class Tree<S> {
public String treeSpec;
public Tree(String treeSpec) {
this.treeSpec=treeSpec;
}
}
import java.util.Iterator;
import java.util.TreeSet;
import java.util.Vector;
public class TreeDemo {
public static void main(String[] args) {
//-----Test Cases ---
Vector<String> treeCollection = new Vector<String>();
treeCollection.addElement( "(A (B (C ) (D) ) (E) (F))");
treeCollection.addElement( "(Any Thing Goes (Big Child (Level 21 (Level 211) (Level 212)) (Level 22)(Level 23 (Level 234 )))(Cxihild Node)( Dooble Words))");
// Running Tests
Iterator<String> tcIter = treeCollection.iterator();
while (tcIter.hasNext()){
System.out.println ("!!!!!! ----- Starting New Tree Build and Traveral ----- !!!!!!");
String treeSpec = tcIter.next();
System.out.println("Tree Specification String = " + treeSpec);
// Build Tree
TreeSet<String> tree = new TreeSet<String> ();
tree.add(treeSpec);
System.out.println("Pre-order Traversal");
// Iterate through Nodes -- PreOrder
Iterator<String> itr = tree.iterator();
while (itr.hasNext())
System.out.println (itr.next());
}
}
}
output
!!!!!! ----- Starting New Tree Build and Traveral ----- !!!!!!
Tree Specification String = (A (B (C ) (D) ) (E) (F))
Pre-order Traversal
(A (B (C ) (D) ) (E) (F))
!!!!!! ----- Starting New Tree Build and Traveral ----- !!!!!!
Tree Specification String = (Any Thing Goes (Big Child (Level 21 (Level 211) (Level 212)) (Level 22)(Level 23 (Level 234 )))(Cxihild Node)( Dooble Words))
Pre-order Traversal
(Any Thing Goes (Big Child (Level 21 (Level 211) (Level 212)) (Level 22)(Level 23 (Level 234 )))(Cxihild Node)( Dooble Words))
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.