Created
April 9, 2019 10:33
-
-
Save ssaurel/daa69df7bb863f6a8a0cbf6470306963 to your computer and use it in GitHub Desktop.
Iterative In Order Traversal in Java on the SSaurel's Channel
This file contains 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
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