Created
April 9, 2019 10:07
-
-
Save ssaurel/84a902fcecd3db63a7f1e0f41fc13c39 to your computer and use it in GitHub Desktop.
Iterative Pre Order Traversal implementation 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 iterativePreOrderTraverse(Node<T> node) { | |
if (node == null) | |
return; | |
// We create an empty stack and we push root to it | |
Stack<Node<T>> nodeStack = new Stack<>(); | |
nodeStack.push(node); | |
// We pop all items one by one. | |
// For each item, we make the following steps : print data, push its right child, push its left child | |
// We push right child in first for that left is processed first | |
while(!nodeStack.empty()) { | |
Node<T> currentNode = nodeStack.pop(); | |
System.out.print(currentNode.data + " "); | |
if (currentNode.right != null) | |
nodeStack.push(currentNode.right); | |
if (currentNode.left != null) | |
nodeStack.push(currentNode.left); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment