Link: http://oj.leetcode.com/problems/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?
Iterative version:
1 /** 2 * Definition for binary tree 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 public class Solution { 11 public ArrayList<Integer> postorderTraversal(TreeNode root) { 12 ArrayList<Integer> nodes = new ArrayList<Integer>(); 13 if (root == null) 14 return nodes; 15 Stack<TreeNode> stack = new Stack<TreeNode>(); 16 TreeNode node; 17 stack.push(root); 18 while (!stack.isEmpty()) { 19 node = stack.pop(); 20 nodes.add(node.val); 21 if (node.left != null) 22 stack.push(node.left); 23 if (node.right != null) 24 stack.push(node.right); 25 } 26 ArrayList<Integer> result = new ArrayList<Integer>(); 27 for (int i = nodes.size() - 1; i >= 0; i--) { 28 result.add(nodes.get(i)); 29 } 30 return result; 31 } 32 }
Recursion version:
1 /** 2 * Definition for binary tree 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 public class Solution { 11 12 ArrayList<Integer> nodes = new ArrayList<Integer>(); 13 14 public ArrayList<Integer> postorderTraversal(TreeNode root) { 15 postorderTraversal_recursion(root); 16 return nodes; 17 } 18 19 public void postorderTraversal_recursion(TreeNode root) { 20 if (root == null) 21 return; 22 postorderTraversal_recursion(root.left); 23 postorderTraversal_recursion(root.right); 24 nodes.add(root.val); 25 } 26 }