# Binary Tree Postorder traversal

Given a binary tree, return the postorder traversal of its nodes’ values.

For example:
Given binary tree {1,#,2,3},

1
\
2
/
3

return [3,2,1].

Note: Recursive solution is trivial, could you do it iteratively?

Among all the three tree traversal methods, the postorder is the tricky one.
There are actually several ways of doing that even besides the recursive one. Here, I will try to introduce the most intuitive and easiest one.

In order to store the order, we need two stacks here instead of one.

Before start, let’s recall how we do the preorder first. In the preorder traversal, we use a stack storing the sequence. The way we push nodes is Right ==> Left. Why? Because we could get the order of Left ==> Right when popping out the node in this way. However, for post order, we need exactly opposite sequence. So, we need to push left child first to the stack and then right.

Given the example above:
1
\
2
/
3
The first stack should be like: 123

We could see this order is totally opposite to the one we need. Because this is the order of root==>right==>left. And what we need for the postorder traversal is: left ==> right ==> root. So that’s why we need another extra stack to reverse the order.

Here is the code:

```/**
* Definition for binary tree
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public ArrayList<Integer> postorderTraversal(TreeNode root) {
ArrayList<Integer> list = new ArrayList<Integer>();
Stack<TreeNode> stack = new Stack<TreeNode>();
Stack<TreeNode> output = new Stack<TreeNode>();

if (root == null) {
return list;
}
stack.push(root);
while(!stack.empty()) {
TreeNode node = stack.pop();
output.push(node);
if (node.left != null) {
stack.push(node.left);
}
if (node.right != null) {
stack.push(node.right);
}
}
while (!output.empty()) {
{"found_math": false, "script_math_tex": 0, "script_math_asciimath": 0, "math_annotations": 0, "math_alttext": 0, "mathml": 0, "mathjax_tag": 0, "mathjax_inline_tex": 0, "mathjax_display_tex": 0, "mathjax_asciimath": 0, "img_math": 0, "codecogs_latex": 0, "wp_latex": 0, "mimetex.cgi": 0, "/images/math/codecogs": 0, "mathtex.cgi": 0, "katex": 0, "math-container": 0, "wp-katex-eq": 0, "align": 0, "equation": 0, "x-ck12": 0, "texerror": 0, "url": "edwardalgorithm.wordpress.com", "fetch_time": 1532255928000000000, "content_mime_type": "text/html", "warc_filename": "crawl-data/CC-MAIN-2018-30/segments/1531676593208.44/warc/CC-MAIN-20180722100513-20180722120513-00530.warc.gz", "warc_record_offset": 647731378, "warc_record_length": 17544, "token_count": 449, "char_count": 1916, "score": 4.03125, "int_score": 4, "crawl": "CC-MAIN-2018-30", "snapshot_type": "latest", "language": "en", "language_score": 0.7538793683052063, "file_path": "/sailhome/yjruan/project/latent-lm/data/processed/finemath-4plus/finemath-4plus/train-00025-of-00064.parquet"}