Skip to content

Instantly share code, notes, and snippets.

@ssaurel
Created April 9, 2019 10:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ssaurel/0ea27008628e8c265a756bac5be5d5d9 to your computer and use it in GitHub Desktop.
Save ssaurel/0ea27008628e8c265a756bac5be5d5d9 to your computer and use it in GitHub Desktop.
Iterative Post Order Traversal Algorithm on the SSaurel's Channel
public static <T> void iterativePostOrderTraverse(Node<T> node) {
if (node == null)
return;
// We create two stacks
Stack<Node<T>> nodeStack1 = new Stack<>();
Stack<Node<T>> nodeStack2 = new Stack<>();
// We push root to first stack
nodeStack1.push(node);
// We iterate while first stack is not empty
while (!nodeStack1.isEmpty()) {
// We pop an item from nodeStack1 and we push it to nodeStack2
Node<T> tmpNode = nodeStack1.pop();
nodeStack2.push(tmpNode);
// We push left and right children of removed item to nodeStack1
if (tmpNode.left != null)
nodeStack1.push(tmpNode.left);
if (tmpNode.right != null)
nodeStack1.push(tmpNode.right);
}
// We print all elements of nodeStack2
while (!nodeStack2.isEmpty()) {
Node<T> tmpNode = nodeStack2.pop();
System.out.print(tmpNode.data + " ");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment