// Returns an Iterator that generates this tree // and all its subtrees, in preorder left-to-right order. public Iterator iterator () { ArrayList a = new ArrayList(); enumerateSubtrees (this, a); // Returning a.iterator() would almost be correct, // but the problem statement requires the remove() // method to throw a certain exception. return new IteratorWithNoRemove(a.iterator()); } // Given a BLT t and an ArrayList, // adds the subtrees of t to the ArrayList. private void enumerateSubtrees (BLT t, ArrayList a) { a.add(t); if (! (t.isLeaf())) { enumerateSubtrees(t.left(), a); enumerateSubtrees(t.right(), a); } } // IteratorWithNoRemove encapsulates an Iterator // and hides its remove() method. private static class IteratorWithNoRemove implements Iterator { // the encapsulated Iterator private Iterator it; IteratorWithNoRemove (Iterator it) { this.it = it; } // the hasNext() method delegates to this.it public boolean hasNext() { return it.hasNext(); } // the next() method delegates to this.it public T next() { return it.next(); } // but the remove() method throws an exception. public void remove() { throw new UnsupportedOperationException(); } }