码迷,mamicode.com
首页 > 其他好文 > 详细

144. Binary Tree Preorder Traversal

时间:2017-10-12 10:08:42      阅读:181      评论:0      收藏:0      [点我收藏+]

标签:class   log   traversal   java   rsa   amp   solution   bsp   logs   

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

标签:class   log   traversal   java   rsa   amp   solution   bsp   logs   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!