Created
August 13, 2013 18:17
-
-
Save nm3mon/6224026 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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