I had so much trouble implementing an iterator who traverses my tree using in-order traversal in an iterative way.

Here below the solution who came up thanks to Ivano and Fabio.

Hope it can helps.

The complete code of BinaryTree is available here (use at your own risk)



private class BinTreeIterator implements Iterator{


private Node p;
private boolean complete;

public BinTreeIterator(Node root) {
p = root;
complete = false;
setNotVisitedNode(root);

// set p to the smallest element of the tree
while (p.getLeftChild() != null)
p = p.getLeftChild();
}

private void setNotVisitedNode(Node n) {
if (n.getLeftChild() != null)
setNotVisitedNode(n.getLeftChild());
n.visited = false;
if (n.getRightChild() != null)
setNotVisitedNode(n.getRightChild());
n.getRightChild();
}

public boolean hasNext() {
return !complete;
}

public T next() {
// check if completed
if(complete)
return null;

Node tmp = p;
p.setVisited(true);

// next node to visit
if (p.getLeftChild() != null && !p.getLeftChild().isVisited())
{
// set p to the smallest element of the tree
while (p.getLeftChild() != null && !p.getLeftChild().isVisited())
p = p.getLeftChild();
}
else if (p.getRightChild() != null && !p.getRightChild().isVisited())
{
p = p.getRightChild();
// set p to the smallest element of the tree
while (p.getLeftChild() != null && !p.getLeftChild().isVisited())
p = p.getLeftChild();
}
else {
// sub tree completed, step back or quit
while(p!=null && p.isVisited())
p=p.getParent();
// check for root
if (p==null)
complete=true;
}
// return current visited node
return tmp.getValue();
}

public void remove() {

}

}