package browser;

import java.util.Iterator;
import java.util.NoSuchElementException;

public class BinaryTree<E> {

	private E data;
	private BinaryTree<E> right = null;
	private BinaryTree<E> left = null;
	private BinaryTree<E> father = null;

	public BinaryTree(E data, BinaryTree<E> left, BinaryTree<E> right) {
		if (left != null && left.father != null || right != null
				&& right.father != null)
			throw new IllegalArgumentException();
		this.data = data;
		this.left = left;
		this.right = right;
		left.father = right.father = this;
	}

	public Iterator<E> postfixeDFS() {
		return new Iterator<E>() {
			BinaryTree<E> next = BinaryTree.this;
			BinaryTree<E> previous = null;

			public boolean hasNext() {
				return next != null;
			}

			private BinaryTree<E> first(BinaryTree<E> root) {
				if (root.left != null)
					return first(root.left);
				else if (root.right != null)
					return first(root.left);
				else
					return root;
			}

			private BinaryTree<E> next(BinaryTree<E> previous) {
				BinaryTree<E> f = previous.father;
				if (f != null && f.left == previous && f.right != null)
					return first(f.right);
				else
					return f;
			}

			public E next() {
				if (next == null)
					throw new NoSuchElementException();
				E result = next.data;
				next = next(next);
				return result;
			}

			@Override
			public void remove() {
				// TODO Auto-generated method stub

			}

		};
	}
}
