102. Binary Tree Level Order Traversal

iteratively and recursively

time: O(n)
space: O(n)

public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        if (root == null) return res;
        
        Queue<TreeNode> q = new LinkedList<TreeNode>();
        q.add(root);
        int left = 1;
        int total = 0;
        List<Integer> tempList = new ArrayList<>();
        while (!q.isEmpty()) {
            TreeNode temp = q.poll();
            left--;
            tempList.add(temp.val);
            
            
            if (temp.left != null) {
                q.add(temp.left);
                total++;
            }
            if (temp.right != null) {
                q.add(temp.right);
                total++;
            }
            if (left == 0) {
                left = total;
                total = 0;
                res.add(tempList);
                tempList = new ArrayList<Integer>();
            }
            
        }
        
        return res;
    }

time: O(n)
space: O(n) 感觉还是这个,因为虽然看起来不用什么数据结构,但是实际上recursion本身在space里就是一个stack

public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        if (root == null) return res;
        
        helper(res,root, 0);
        return res;
        
    }
    
    public void helper(List<List<Integer>> res, TreeNode root, int level) {
        if (root == null) return;
        
        if (level == res.size()) {
            List<Integer> tempList = new ArrayList<>();
            tempList.add(root.val);
            res.add(tempList);
        } else {
            res.get(level).add(root.val);
        }
        
        helper(res, root.left, level+1);
        helper(res, root.right, level+1);
        
    }
posted @ 2016-11-04 12:40  哇呀呀..生气啦~  阅读(71)  评论(0)    收藏  举报