import java.util.Iterator; import java.util.NoSuchElementException; import structure5.*; /** * Implements an in-order traversal of a BinarySearchTree. * Implementing this iterator is much easier if you use the * BST in Bailey, Ch. 13, which keeps track of parents. * Since we don't have parents available, we instead use * a Stack. Alternatively, we could have written this * recursively using a helper method. */ public class BinarySearchTreeIterator> implements Iterator { BinarySearchTree bst; BinarySearchTree cur; Stack> parents; public BinarySearchTreeIterator(BinarySearchTree bst) { this.bst = bst; this.cur = null; parents = new StackList>(); // set cur to the leftmost node cur = bst; if (cur == null) return; while(cur.getLeft() != null) { parents.add(cur); cur = cur.getLeft(); } } public boolean hasNext() { return cur != null; } public T next() { if (!hasNext()) { throw new NoSuchElementException(); } // invariant: cur is always the leftmost node BinarySearchTree tmp = cur; // if there is a right side, go right, then // go as far left as possible if (cur.getRight() != null) { parents.add(cur); cur = cur.getRight(); // get leftmost node while (cur.getLeft() != null) { parents.add(cur); cur = cur.getLeft(); } // no right child; find the first parent from the left } else if (parents.isEmpty()) { cur = null; // done } else { // keep popping until we come from the left BinarySearchTree prev = cur; while(true) { cur = parents.pop(); if (cur.getLeft() == prev) { break; } prev = cur; } } // return the current value return tmp.getValue(); } public void remove() { // do nothing for now } }