// Returns an Iterator that generates this tree // and all its subtrees, in preorder left-to-right order. public Iterator iterator () { return new IteratorOfBLTs(this); } // Instances of this class generate all subtrees of a BLT. private static class IteratorOfBLTs implements Iterator { // a stack that contains // all BLTs whose subtrees have not yet been generated private Stack stk; IteratorOfBLTs (BLT t) { this.stk = new Stack(); this.stk.push(t); } // Are there more subtrees to be generated? public boolean hasNext() { return ! (stk.empty()); } // Returns the next subtree to be generated, // in preorder, left-to-right order. public BLT next() { if (hasNext()) { BLT t = stk.pop(); if (! (t.isLeaf())) { stk.push(t.right()); stk.push(t.left()); } return t; } else throw new NoSuchElementException(); } // Always throws an exception. public void remove() { throw new UnsupportedOperationException(); } }