Skip to content

Instantly share code, notes, and snippets.

@ssaurel
Created April 9, 2019 10:33
Show Gist options
  • Save ssaurel/daa69df7bb863f6a8a0cbf6470306963 to your computer and use it in GitHub Desktop.
Save ssaurel/daa69df7bb863f6a8a0cbf6470306963 to your computer and use it in GitHub Desktop.
Iterative In Order Traversal in Java on the SSaurel's Channel
public static <T> void iterativeInOrderTraverse(Node<T> node) {
if (node == null)
return;
// We create an empty stack
Stack<Node<T>> nodeStack = new Stack<>();
Node<T> currentNode = node;
// We traverse the tree
while (currentNode != null || nodeStack.size() > 0) {
// We try to reach the most left node of the current node
while (currentNode != null) {
// We add the pointer to the stack before traversing to the left node
nodeStack.push(currentNode);
currentNode = currentNode.left;
}
// Current Node is null a this point
currentNode = nodeStack.pop();
System.out.print(currentNode.data + " ");
// Now, it's time to visit the right subtree
currentNode = currentNode.right;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment