144. Binary Tree Preorder Traversal

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;
    }
}

  

posted @ 2017-10-12 06:04  Weiyu Wang  阅读(75)  评论(0编辑  收藏  举报