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?
第二遍写postOrder竟然有点忘记了,更惨的是preOrder竟然半个小时都没写出来。看来还是要经过思考才能够记得牢固,之前对preOrder,postOrder都是看文章然后再理解,所以有些逻辑没有好好理清楚。
下面上代码:
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
TreeNode tmp=null,node=null;
List<TreeNode> list = new ArrayList<TreeNode>();
List<Integer> res = new ArrayList<Integer>();
if(root==null)
{
return res;
}else
{
tmp = root;
// remember the add element
list.add(tmp);
// remember loop condition
while(list.size()>0)
{
tmp = list.get(list.size()-1);
<span style="white-space:pre"> </span>// the condition to add the node
if((tmp.right==null&&tmp.left==null) ||
(node!=null &&(node==tmp.left || node==tmp.right)))
{
list.remove(list.size()-1);
res.add(tmp.val);
node = tmp;
}else
{
if(tmp.right!=null)
{
list.add(tmp.right);
}
if(tmp.left!=null)
{
list.add(tmp.left);
}
}
}
}
// remember the return value
return res;
}
}