以下は、葉ノード、つまり左または右のサブツリーを持たないノードのみを返す Iterator を実装する方法です。
イテレータは、深さ優先検索を実行してツリー内のリーフ ノードを検索し、スタック内の検索の現在の状態を記憶し、リーフ ノードが見つかったときに「一時停止」します (fetchNext() メソッドを参照)。
クライアントが next() を呼び出してリーフ ノードを「消費」すると、検索が再開されます。
class Node {
public Node left;
public Node right;
}
class LeaveIterator implements Iterator<Node> {
private final Stack<Node> stack = new Stack<>();
private Node nextNode = null;
public LeaveIterator(Node root) {
if (root != null) {
stack.push(root);
nextNode = fetchNext();
}
}
private void fetchNext() {
Node next = null;
while (!stack.isEmpty() && next == null) {
Node node = stack.pop();
if (node.left == null && node.right == null) {
next = node;
}
if (node.right != null) {
stack.push(node.right);
}
if (node.left != null) {
stack.push(node.left);
}
}
return next;
}
public boolean hasNext() {
return nextNode != null;
}
public Node next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
Node n = nextNode;
nextNode = fetchNext();
return n;
}
public void remove() {
throw new UnsupportedOperationException();
}
}