Skip to content

Instantly share code, notes, and snippets.

@ssaurel
Created April 9, 2019 10:07
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Embed
What would you like to do?
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