leetcode Binary Tree Postorder Traversal

Binary Tree Postorder Traversal

  Total Accepted: 23892  Total Submissions: 77206 My Submissions

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?

Have you been asked this question in an interview? 

Discuss


第二遍写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;
    }
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值