144. Binary Tree Preorder Traversal

144. Binary Tree Preorder Traversal


////// wrong 

class Solution {
    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        Deque<TreeNode> stack = new LinkedList<>();
        if(root == null){
            return result;
        }
        stack.offer(root);
        while(!stack.isEmpty()){
            TreeNode cur = stack.poll();
            result.add(cur.val);
            if(cur.right != null){
                stack.offer(cur.right);
            }
            if(cur.left != null){
                stack.offer(cur.left);
            }
        }
        return result;
    }
}



//// this Is okay . Idk why 

class Solution {
    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        Deque<TreeNode> stack = new LinkedList<>();
        if(root == null){
            return result;
        }
        stack.push(root);
        while(!stack.isEmpty()){
            TreeNode cur = stack.pop();
            result.add(cur.val);
            if(cur.right != null){
                stack.push(cur.right);
            }
            if(cur.left != null){
                stack.push(cur.left);
            }
        }
        return result;
    }
}



//////  correct 
class Solution {
   List<Integer> result = new ArrayList<>();
   public List<Integer> preorderTraversal(TreeNode root) {
       
        if(root == null){
            return result;
        }
        result.add(root.val);
        preorderTraversal(root.left);
        preorderTraversal(root.right);
        return result;
    }
}

///// wrong , because 
 class Solution {
   
   public List<Integer> preorderTraversal(TreeNode root) {
    List<Integer> result = new ArrayList<>();/////// . should be a global var , should be placed above 
       
        if(root == null){
            return result;
        }
        result.add(root.val);
        preorderTraversal(root.left);
        preorderTraversal(root.right);
        return result;
    }
}

Given a binary tree, return the preorder traversal of its nodes' values.

Example:

Input: [1,null,2,3]
   1
    \
     2
    /
   3

Output: [1,2,3]

Follow up: Recursive solution is trivial, could you do it iteratively?

 

 

posted on 2018-07-19 12:41  猪猪&#128055;  阅读(125)  评论(0)    收藏  举报

导航