方法一:递归的方法
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { public List<Integer> postorderTraversal(TreeNode root) { List<Integer> arraylist=new ArrayList<Integer>(); if(root==null){ return arraylist; } List<Integer> left=postorderTraversal(root.left); List<Integer> right=postorderTraversal(root.right); arraylist.addAll(left); arraylist.addAll(right); arraylist.add(root.val); return arraylist; } }
方法二:迭代的方法
class Solution { public List<Integer> postorderTraversal(TreeNode root) { Stack<TreeNode> stack=new Stack<>(); List<Integer> list=new ArrayList<Integer>(); TreeNode cur=root; TreeNode p=null; //用来记录上一个节点 while(!stack.isEmpty()||cur!=null){ while(cur!=null){ stack.push(cur); cur=cur.left; } cur=stack.peek(); if(cur.right==null||cur.right==p){ list.add(cur.val); stack.pop(); p=cur; cur=null; }else{ cur=cur.right; } } return list; } }