/** * A simple example of using the Tree interface described earlier. We * create the tree of Figure 1 and then compare the expected and * actual results of some of the methods applied to that tree. The * tests are not exhaustive and are only meant to provide a brief example * of the use of the interface. */ public class TestMyTree { // We use the following for accesses from the main method. static TreeNode four, seven, eight, ten, eleven, twenty; public static void main(String[] args) { Tree tree = createFigure1Tree(); // Ouput format: Expected - Actual System.out.print("Preorder tree traversal: 1,2,3,4,5,6,7,8,9,10,11 - "); tree.printPreOrder(); System.out .print("Postorder tree traversal: 4,5,6,3,7,2,10,9,11,8,1 - "); tree.printPostOrder(); // Ouput format: Expected,Actual System.out.println("Tree root: 1," + tree.getRoot()); System.out.println("Tree size: 11," + tree.size()); System.out.println("Size of 10: 1," + ten.size()); System.out.println("Size of 8: 4," + eight.size()); System.out.println("Tree height: 3," + tree.height()); System.out.println("Height of 1: 3," + tree.getRoot().height()); System.out.println("Height of 7: 0," + tree.height(seven)); System.out.println("Height of 8: 2," + tree.height(eight)); System.out.println("Height of 10: 0," + tree.height(ten)); System.out.println("Depth of 20: -1," + tree.depth(twenty)); System.out.println("Depth of 1: 0," + tree.depth(tree.getRoot())); System.out.println("Depth of 4: 3," + tree.depth(four)); System.out.println("Depth of 11: 2," + tree.depth(eleven)); System.out.println("Depth of 10: 3," + tree.depth(ten)); System.out.println("Depth of 20: -1," + tree.depth(twenty)); System.out.println("Is empty: false," + tree.isEmpty()); tree.makeEmpty(); System.out.println("Is empty: true," + tree.isEmpty()); } /** * Create the tree from Figure 1. * * @return new Figure 1 tree. */ private static Tree createFigure1Tree() { TreeNode three = new MyTreeNode(3); four = new MyTreeNode(4); three.addChild(four); three.addChild(new MyTreeNode(5)); three.addChild(new MyTreeNode(6)); TreeNode two = new MyTreeNode(2); two.addChild(three); seven = new MyTreeNode(7); two.addChild(seven); eight = new MyTreeNode(8); eight.addChild(new MyTreeNode(9)); ten = new MyTreeNode(10); eight.getChildren().get(0).addChild(ten); eleven = new MyTreeNode(11); eight.addChild(eleven); TreeNode root = new MyTreeNode(1); root.addChild(two); root.addChild(eight); return new MyTree(root); } }