Engineering Full Stack Apps with Java and JavaScript
We can do post order traversal iteratively using two stacks.
There are also approaches involving one stack, but this seems to be a simpler one to understand.
For a root element T1 with left child T2 and right child T3, post order traversal order will be T2, T3, and T1.
To make this happen, we should elements in the order T1, T2 and T3 into the second stack and then print them.
Approach can be summarized as:
Create two stacks s1 and s2.
Push root to first stack s1.
Loop while first stack s1 is not empty:
Pop a node from first stack s1 and push it to second stack s2
Push left and right children of the popped node to first stack s1
Print contents of second stack s2
void postorder(TreeNode n)
{
TreeNode current = n;
Stack s1 = new Stack();
Stack s2 = new Stack();
s1.push(current);
while(!s1.isEmpty())
{
current = s1.pop();
s2.push(current);
s1.push(current.left);
s1.push(current.right);
}
while(!s2.isEmpty())
{
current = s2.pop();
print(current);
}
}
Complexity
Time complexity will be in the order of N.
However, extra spaces will be taken for two stacks.