import java.util.Iterator; import java.util.NoSuchElementException; /* Iterates over the children of a position in the tree, from left to right. */ public class TreeChildrenIterator implements Iterator { protected TreeNode p; // next position to return, or null if no more public TreeChildrenIterator(TreeNode p) { this.p = p.leftChild(); } public boolean hasNext() { return (p != null); } public Object next() { return nextPosition().element(); } public TreeNode nextPosition() { if (!hasNext()) throw new NoSuchElementException(); TreeNode old = p; // we will return old p = p.rightSibling(); return old; } /* The java.util.Iterator interface requires us to define a method for destructively removing an element from the list being iterated over, but we are allowed to just throw an UnsupportedOperationException if we don't want to implement this. */ public void remove() { throw new UnsupportedOperationException(); } }