Skip to content

Instantly share code, notes, and snippets.

@ssaurel
Created April 9, 2019 10:07
Show Gist options
  • Save ssaurel/84a902fcecd3db63a7f1e0f41fc13c39 to your computer and use it in GitHub Desktop.
Save ssaurel/84a902fcecd3db63a7f1e0f41fc13c39 to your computer and use it in GitHub Desktop.
Iterative Pre Order Traversal implementation on the SSaurel's Channel
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