import java.util.Iterator; import java.util.Deque; import java.util.ArrayDeque; /** * An iterator for binary trees that visits elements in a * pre-order manner (current node, then left subtree, then right subtree). * Basic idea is to maintain a stack of nodes to visit, and each time * a tree/subtree is processed, first visit the node itself, then add the right * and left subtrees to the todo list (stack). */ public class PreorderIterator implements Iterator { // stack of nodes to visit private Deque> todo; // set up the stack public PreorderIterator(BinaryTree tree) { todo = new ArrayDeque>(); todo.push(tree); } // 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(); // push right subtree if (!top.right().isEmpty()) { todo.push(top.right()); } // push left subtree (LIFO ordering, so this is next) if (!top.left().isEmpty()) { todo.push(top.left()); } 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); PreorderIterator iter = new PreorderIterator(green); while (iter.hasNext()) { System.out.println(iter.next()); } } }