Rev 24 | Rev 26 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed
// Written by Ira Snyder// 11-03-2004import java.io.*;import java.util.*;class UnorderedTree {private Object root;private Set subtrees;private int size;public UnorderedTree( ) { } //constructs an empty treepublic UnorderedTree( Object root ) { //constructs a singletonthis.root = root;subtrees = new HashSet(); //empty setsize = 1;}//constructor to create any tree that is not a singleton//and is not an empty treepublic UnorderedTree( Object root, Set trees ) {this(root);for( Iterator it=trees.iterator(); it.hasNext(); ) {Object object = it.next();if( object instanceof UnorderedTree ) {UnorderedTree tree = (UnorderedTree)object;subtrees.add(tree);size += tree.size;}}}public int size( ) { return size; }public void printPreOrder( PrintStream ps ) {printPreOrderHelper( ps, this ); //print the whole tree in preorderps.println(); //end the line}public static void printPreOrderHelper( PrintStream ps, UnorderedTree tree ) {ps.print( tree.root + " " ); //print the nodefor( Iterator it=tree.subtrees.iterator(); it.hasNext(); ) {//recurse subtrees in preorderprintPreOrderHelper( ps, (UnorderedTree)it.next() );}}public void printPostOrder( PrintStream ps ) {printPostOrderHelper( ps, this ); //print the whole tree in postorderps.println(); //end the line}public static void printPostOrderHelper( PrintStream ps, UnorderedTree tree ) {for( Iterator it=tree.subtrees.iterator(); it.hasNext(); ) {//recurse subtrees in postorderprintPostOrderHelper( ps, (UnorderedTree)it.next() );}ps.print( tree.root + " "); //print the node}public void printLevelOrder( PrintStream ps ) {Queue q = new Queue();q.enqueue(this); //add the rootwhile( !q.isEmpty() ) {//remove the first item in the queueUnorderedTree temp = (UnorderedTree)q.dequeue();ps.print(temp.root + " "); //visit the node//add all the children of temp to the queuefor( Iterator it=temp.subtrees.iterator(); it.hasNext(); ) {q.enqueue( it.next() );}}ps.println(); //end the current line}} //end class UnorderedTree