Rev 23 | Blame | Last modification | View Log | RSS feed
// Written by Ira Snyder
// 11-03-2004
import java.io.*;
import java.util.*;
class UnorderedTree {
private Object root;
private Set subtrees;
private int size;
public UnorderedTree( ) { } //constructs an empty tree
public UnorderedTree( Object root ) { //constructs a singleton
this.root = root;
subtrees = new HashSet(); //empty set
size = 1;
}
//constructor to create any tree that is not a singleton
//and is not an empty tree
public 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 preorder
ps.println(); //end the line
}
public static void printPreOrderHelper( PrintStream ps, UnorderedTree tree ) {
ps.print( tree.root + " " ); //print the node
for( Iterator it=tree.subtrees.iterator(); it.hasNext(); ) {
//recurse subtrees in preorder
printPreOrderHelper( ps, (UnorderedTree)it.next() );
}
}
public void printPostOrder( PrintStream ps ) {
printPostOrderHelper( ps, this ); //print the whole tree in postorder
ps.println(); //end the line
}
public static void printPostOrderHelper( PrintStream ps, UnorderedTree tree ) {
for( Iterator it=tree.subtrees.iterator(); it.hasNext(); ) {
//recurse subtrees in postorder
printPostOrderHelper( 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 root
while( !q.isEmpty() ) {
//remove the first item in the queue
UnorderedTree temp = (UnorderedTree)q.dequeue();
ps.print(temp.root + " "); //visit the node
//add all the children of temp to the queue
for( Iterator it=temp.subtrees.iterator(); it.hasNext(); ) {
q.enqueue( it.next() );
}
}
ps.println(); //end the current line
}
} //end class UnorderedTree