Skip to content

Instantly share code, notes, and snippets.

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
You can’t perform that action at this time.