1 public class Solution {
2 public ArrayList<Integer> postorderTraversal(TreeNode root) {
3 ArrayList<Integer> res = new ArrayList<Integer>();
4 if(root==null) return res;
5 TreeNode cur = null, pre = null;
6 Stack<TreeNode>stack = new Stack<TreeNode>();
7 stack.push(root);
8 while(!stack.isEmpty()){
9 cur = stack.peek();
10 if((cur.right==null && cur.left==null) ||(pre!=null && (cur.right==pre || cur.left==pre))){
11 res.add(cur.val);
12 pre = cur;
13 stack.pop();
14 }else{
15 if(cur.right!=null){
16 stack.push(cur.right);
17 }
18 if(cur.left!=null){
19 stack.push(cur.left);
20 }
21 }
22 }
23 return res;
24 }
25 }