Skip to content

Instantly share code, notes, and snippets.

@nm3mon
Created August 13, 2013 18:17
Show Gist options
  • Save nm3mon/6224026 to your computer and use it in GitHub Desktop.
Save nm3mon/6224026 to your computer and use it in GitHub Desktop.
class Node<E> {
E data;
Node<E> left;
Node<E> right;
E getData() {return data;}
Node<E> leftChild() {return this.left;}
Node<E> rightChild() {return this.right;}
}
static <T> void iterateBSTInOrder(Node<T> node) {
boolean done = false;
Node<T> nodePtr = node;
Stack<Node<T>> stack = new Stack<>();
while (!done) {
//until done, keep looking for left child
if (nodePtr != null) {
stack.push(nodePtr);
nodePtr = nodePtr.leftChild();
}
else {
//if no leftChild remains, go into right subtree and find left children
if (!stack.isEmpty()) {
nodePtr = stack.pop();
System.out.println(nodePtr.getData());
nodePtr = nodePtr.rightChild();
}
else {
//if there's nothing left in the stack, we've already traversed the entire tree
done = true;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment