首页 > 其他 > 详细

144. Binary Tree Preorder Traversal

时间:2017-10-12 09:54:14      阅读:252      评论:0      收藏:0      [点我收藏+]
class Solution {
    public List<Integer> preorderTraversal(TreeNode root) {
        Stack<TreeNode> stack=new Stack<TreeNode>();
        List<Integer> res=new ArrayList<Integer>();
        while(root!=null||!stack.isEmpty())
        {
            while(root!=null)
            {
                res.add(root.val);
                stack.push(root);
                root=root.left;
            }
            root=stack.pop().right;
        }
        return res;
    }
}

 

class Solution {
    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> res=new ArrayList<Integer>();
        TreeNode cur=root, pre=null;
        while(cur!=null)
        {
            if(cur.left==null)
            {
                res.add(cur.val);
                cur=cur.right;
            }
            else
            {
                pre=cur.left;
                while(pre.right!=null&&pre.right!=cur)
                    pre=pre.right;
                if(pre.right==null)
                {
                    res.add(cur.val);
                    pre.right=cur;
                    cur=cur.left;
                }
                else
                {
                    pre.right=null;
                    cur=cur.right;
                }
            }
        }
        return res;
    }
}

  

144. Binary Tree Preorder Traversal

原文:http://www.cnblogs.com/asuran/p/7654352.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!