/** * 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> ret = new ArrayList<Integer>(); if(root==null)return ret; Stack<TreeNode> stack = new Stack<TreeNode>(); stack.push(root); while(!stack.isEmpty()){ TreeNode now = stack.peek(); if(now.right==null && now.left==null){ ret.add(now.val); stack.pop(); } else{ if(now.right!=null){ stack.push(now.right); now.right=null; } if(now.left!=null){ stack.push(now.left); now.left=null; } } } return ret; } }