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 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> res = new ArrayList<Integer>(); if(root == null) return res; recursion(res,root); return res; } public void recursion(ArrayList<Integer> res, TreeNode root) { if(root.left != null) { recursion(res,root.left); } if(root.right != null) { recursion(res,root.right); } res.add(root.val); } }