// StringTreeIterateChild.java // extends the Tree class with an iterator over the children of the // owner. // One would think this could be done generically, but that seems to get the // compiler hopelessly confused import java.util.Iterator; class StringTreeIterateChild extends Tree implements Iterable> { @Override // Iterates through the children of this. public Iterator> iterator() { Iterator> ic = new Iterator>() { private boolean noChildren = (getFirstChild() == null); private Tree c = getFirstChild(); // Keeps track of your place on list @Override public boolean hasNext() { if (noChildren) return false; else return (c != null); } @Override public Tree next() { Tree d = c; c = c.getNextSibling(); return d; } @Override public void remove() { // stub } }; return ic; } // Create a tree labelled by strings. Each interior node has 3 children // level is the depth of the subtree being created. // If the label on nodes n is w, then the label on the children of n is // w + "a", w + "b", and w + "c" // public static StringTreeIterateChild ternaryTree(String key, int level) { if (level < 0) return null; StringTreeIterateChild n = new StringTreeIterateChild(); n.setLabel(key); if (level > 0) { n.addChild(ternaryTree(key + "c", level-1)); n.addChild(ternaryTree(key + "b", level-1)); n.addChild(ternaryTree(key + "a", level-1)); } return n; } public static void main(String[] args) { StringTreeIterateChild n = ternaryTree("",3); for (Tree c : n) System.out.print(c.getLabel() + " "); System.out.println(); n = (StringTreeIterateChild) n.getFirstChild().getFirstChild(); for (Tree c : n) System.out.print(c.getLabel() + " "); System.out.println(); } }