// Source code example for "A Practical Introduction // to Data Structures and Algorithm Analysis" // by Clifford A. Shaffer, Prentice Hall, 1998. // Copyright 1998 by Clifford A. Shaffer import java.io.*; // Driver class for general tree implementation test public class GTmain { // Method for printing out a general tree. // This both tests the implementation, and shows off // how to use the ADT. static void preorder(GTNode rt) { // Preorder traversal if (rt.isLeaf()) System.out.print("Leaf: "); else System.out.print("Internal: "); System.out.println(rt.value()); // Print or take other action GTNode temp = rt.leftmost_child(); while (temp != null) { preorder(temp); temp = temp.right_sibling(); } } // Main routine for general tree test driver public static void main(String args[]) throws IOException { // Build a couple of trees, with printouts along the // way to test that everything is OK. // Ideally, the GTNode would be packaged private from // the application program, and all accesses would be // through the GenTree interface. But, I just want to // test the functions in a simple way. GenTree tree = new GenTreeImpl(); GTNode ptr; GenTree tree2 = new GenTreeImpl(); GTNode ptr2; tree.newroot(new IElem(1), null, null); ptr = tree.root(); System.out.println("Print the tree with one node"); preorder(tree.root()); ptr.insert_first(new GTNodeImpl(new IElem(2))); System.out.println("Print the tree with two nodes"); preorder(tree.root()); ptr = ptr.leftmost_child(); System.out.println("ptr now at node " + ptr.value()); ptr.insert_next(new GTNodeImpl(new IElem(3))); System.out.println("Print the tree with three nodes"); preorder(tree.root()); ptr.insert_next(new GTNodeImpl(new IElem(4))); System.out.println("Print the tree with four nodes"); preorder(tree.root()); ptr = ptr.right_sibling(); System.out.println("ptr now at node " + ptr.value()); ptr.insert_first(new GTNodeImpl(new IElem(5))); System.out.println("Print the tree with 5 nodes"); preorder(tree.root()); tree2.newroot(new IElem(11), null, null); ptr2 = tree2.root(); ptr2.insert_first(new GTNodeImpl(new IElem(12))); ptr2 = ptr2.leftmost_child(); ptr2.insert_next(new GTNodeImpl(new IElem(13))); System.out.println("Print the tree"); preorder(tree2.root()); System.out.println("This is the same tree with 42 added."); tree2.newleftchild(new IElem(42)); preorder(tree2.root()); System.in.read(); } }