Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.