import java.util.ArrayList; import java.util.Iterator; public class Tree { private Node root; int numNodes; // Create a tree with just one node. public Tree(Item value) { root = new Node(value); numNodes = 1; } // A more useful constructor that will create a new tree with a // given node as the root, along with 2 existing subtrees as its children. public Tree(Item value, Tree leftSubtree, Tree rightSubtree) { root = new Node(value); root.left = leftSubtree.root; root.right = rightSubtree.root; leftSubtree.root.parent = root; rightSubtree.root.parent = root; numNodes = leftSubtree.numNodes + rightSubtree.numNodes + 1; } public int size() { return numNodes; } // Let's use the preorder iterator to print the tree! public String toString() { StringBuilder build = new StringBuilder(); Iterator iter = preorderIterator(root); while(iter.hasNext()) build.append("\t" + ((Node)(iter.next())).data + "\n"); return build.toString(); } class PreorderIterator implements Iterator { private ArrayList list; private int currentIndex; // Initialize our attributes to keep track of nodes in preorder, // and start the recursive process from the 'start' node. public PreorderIterator(Node start) { list = new ArrayList(); addNext(start); currentIndex = 0; } // Recursive function to add nodes in a preorder manner public void addNext(Node n) { if (n == null) return; list.add(n); addNext(n.left); addNext(n.right); } public boolean hasNext() { return currentIndex < list.size(); } public Object next() { return list.get(currentIndex++); } public void remove() { throw new UnsupportedOperationException(); } } public Iterator preorderIterator(Node start) { return new PreorderIterator(start); } }