class Node { private Object item; private Node firstChild; private Node lastChild; private Node nextSibling; public Node(Object item) { this.item = item; firstChild = null; lastChild = null; nextSibling = null; } public void addChild(Node n) { if (firstChild == null) firstChild = n; if (lastChild != null) lastChild.nextSibling = n; lastChild = n; } private void visit() { System.out.print(item + " "); } public void preorder() { visit(); for (Node n = firstChild; n != null; n = n.nextSibling) n.preorder(); } public void postorder() { for (Node n = firstChild; n != null; n = n.nextSibling) n.postorder(); visit(); } public int size() { int size = 1; for (Node n = firstChild; n != null; n = n.nextSibling) size += n.size(); return size; } public int height() { int height = -1; for (Node n = firstChild; n != null; n = n.nextSibling) if (n.height() > height) height = n.height(); return height + 1; } } class Tree { public static Node makeTree() { Node root = new Node("root"); Node student = new Node("student"); root.addChild(student); Node name = new Node("name"); Node address = new Node("address"); Node major = new Node("major"); student.addChild(name); student.addChild(address); student.addChild(major); name.addChild(new Node("Bill White")); address.addChild(new Node("300 West 721 North Provo, UT 84604")); major.addChild(new Node("Computer Science")); return root; } public static Node buildTree() { Node a = new Node("A"); Node b = new Node("B"); Node c = new Node("C"); Node d = new Node("D"); Node e = new Node("E"); Node f = new Node("F"); Node g = new Node("G"); Node h = new Node("H"); Node i = new Node("I"); Node j = new Node("J"); Node k = new Node("K"); a.addChild( b ); a.addChild( c ); a.addChild( d ); a.addChild( e ); b.addChild( f ); b.addChild( g ); d.addChild( h ); e.addChild( i ); e.addChild( j ); j.addChild( k ); return a; } public static void main(String[] args) { // Node tree = makeTree(); Node tree = buildTree(); System.out.println("Preorder"); tree.preorder(); System.out.println(); System.out.println("Postorder"); tree.postorder(); System.out.println(); System.out.println("size " + tree.size()); System.out.println("height " + tree.height()); } }