So I am familiar with postorder traversing:
L -> R -> P (Left to Right to Parent).
I saw a code that could perform a postorder traversal quite elegantly using 2 stacks:
public void postOrderTransverse(Node r){
if(r == null){return;}
Stack<Node> s = new Stack<Node>();
Stack<Node> reverser = new Stack<Node>();
s.push(r);
while(!s.isEmpty()){
Node temp = s.pop();
reverser.push(temp);
if (temp.left != null){
s.push(temp.left);}
if(temp.right != null){
s.push(temp.right);}
}
while(!reverser.empty()){
System.out.print(reverser.peek());
reverser.pop();
}
}
(via http://articles.leetcode.com/binary-tree-post-order-traversal/)
where essentially, one Stack just reverses the other. I am just very curious about how this works. I have a hypothesis that Stack s accepts input so that the output would be something like P -> R -> L, and it just passes that onto Stack reverser which spits out L -> R .-> P since it's Last In First Out.
However, just trying to think through the processes of this algorithm, I'm struggling to understand how and why Stack s takes its input the way it does. Hoping I could get some insight on here! Thanks :)