Iterative Post Order Traversal Algorithm on the SSaurel's Channel
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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