import java.util.Iterator; import java.util.Deque; import java.util.ArrayDeque; /** * An iterator for binary trees that visits elements in an * in-order manner (current node, then left subtree, then right subtree). * Here, the key idea is that when we process a tree/subtree, *before* * we visit the node itself, we first walk through all left descendants * adding them to the todo list. */ public class InorderIterator implements Iterator { // stack of nodes to visit private Deque> todo; // set up the stack public InorderIterator(BinaryTree tree) { todo = new ArrayDeque>(); // push all left descendants into todo processLeft(tree); } // push all left descendants starting at current onto todo private void processLeft(BinaryTree current) { while (!current.isEmpty()) { todo.push(current); current = current.left(); } } // not done while the stack still has nodes to visit public boolean hasNext() { return !todo.isEmpty(); } public T next() { // top value is the next element BinaryTree top = todo.pop(); T result = top.value(); // the left subtree was already processed previously, // so we only need to worry about the right subtree now if (!top.right().isEmpty()) { // since this is an in-order traversal, // we push all left descendants (just as we did with the root). processLeft(top.right()); } return result; } public static void main(String args[]) { BinaryTree blue = new BinaryTree("blue"); BinaryTree indigo = new BinaryTree("indigo"); BinaryTree red = new BinaryTree("red"); BinaryTree yellow = new BinaryTree("yellow"); BinaryTree orange = new BinaryTree("orange", indigo, red); BinaryTree violet = new BinaryTree("violet", orange, yellow); BinaryTree green = new BinaryTree("green", blue, violet); InorderIterator iter = new InorderIterator(green); while (iter.hasNext()) { System.out.println(iter.next()); } } }