# LeetCode 145 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?

/**
* Definition for a binary tree node.
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/
public class Solution {

public void DFS(TreeNode root, List<Integer> ans) {
if(root == null) {
return;
}
DFS(root.left, ans);
DFS(root.right, ans);
}

public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> ans = new ArrayList<>();
DFS(root, ans);
return ans;
}
}

/**
* Definition for a binary tree node.
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/
public class Solution {

public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> ans = new ArrayList<>();
Stack<TreeNode> stk = new Stack<>();
if(root != null) {
stk.push(root);
}
TreeNode cur = null;
TreeNode pre = null;
while(!stk.empty()) {
cur = stk.peek();
if(cur.left == null && cur.right == null) {
pre = cur;
stk.pop();
}
else if(pre != null && (cur.left == pre || cur.right == pre)) {
pre = cur;
stk.pop();
}
else {
if(cur.right != null) {
stk.push(cur.right);
}
if(cur.left != null) {
stk.push(cur.left);
}
}
}
return ans;
}
}

05-23 1096

01-16 3872

07-09 1022

05-25 5734

08-19 2504

06-02 752

06-25 27

09-11 3375

08-09 2495

04-24 1.2万