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?
Ref: http://www.cnblogs.com/feiling/p/3426486.html
[解题思路]
后序遍历的非递归相对来说比较难,根节点需要在其左右孩子都访问结束后才能被访问,因此对于任一节点,先将其入栈,如果p不存在左孩子和右孩子,则可以直接访问它;或者p存在左孩子或者右孩子,但是其左孩子和右孩子都已被访问过了,则同样可以直接访问该节点。若非上述两种情况,则将p的右孩子和左孩子依次入栈,这样就保证了每次去站定元素的时候,左孩子在右孩子前面被访问,左孩子和右孩子在根节点前面被访问。
Iteration
/** * 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> result = new ArrayList<Integer>(); if(root == null){ return result; } Stack<TreeNode> stack = new Stack<TreeNode>(); TreeNode cur = null, pre = null; stack.push(root); while(!stack.empty()){ cur = stack.peek(); // pre 用来记录上一个访问的节点,防止root 重复访问左节点和右节点 // (cur.left == pre || cur.right == pre) 可能root的右子为空,所以 // 上一个访问的就为左节点 if((cur.left == null && cur.right == null) || ((pre != null) && (cur.left == pre || cur.right == pre))){ result.add(cur.val); pre = cur; stack.pop(); } else { if(cur.right != null){ stack.push(cur.right); } if(cur.left != null){ stack.push(cur.left); } } } return result; } }
Recursion
/** * 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> result = new ArrayList<Integer>(); if(root == null) return result; if(root.left != null){ result.addAll(postorderTraversal(root.left)); } if(root.right != null){ result.addAll(postorderTraversal(root.right)); } result.add(root.val); return result; } }
DP
/** * 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> result = new ArrayList<Integer>(); postorder(root, result); return result; } private void postorder(TreeNode root, ArrayList<Integer> result){ if(root != null){ postorder(root.left, result); postorder(root.right, result); result.add(root.val); } } }