Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.