LeetCode 103: Binary Tree Zigzag Level Order Traversal

/**
 * 103. Binary Tree Zigzag Level Order Traversal
 * 1. Time:O(n)  Space:O(n)
 * 2. Time:O(n)  Space:O(n)
 */

// 1. Time:O(n)  Space:O(n)
class Solution {
    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        List<List<Integer>> res = new ArrayList<>();
        helper(root,1,res,true);
        return res;
    }
    
    private void helper(TreeNode root,int level,List<List<Integer>> res,boolean order){
        if(root==null) return;
        if(level>res.size())
            res.add(new ArrayList<>());
        if(order) res.get(level-1).add(root.val);
        else res.get(level-1).add(0,root.val);
        helper(root.left,level+1,res,!order);
        helper(root.right,level+1,res,!order);
    }
}

// 2. Time:O(n)  Space:O(n)
class Solution {
    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        List<List<Integer>> res = new ArrayList<>();
        if(root==null) return res;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        boolean order = true;
        while(!queue.isEmpty()){
            ArrayList<Integer> level = new ArrayList<>();
            int cnt = queue.size();
            for(int i=0;i<cnt;i++){
                TreeNode tmp = queue.poll();
                if(order) level.add(tmp.val);
                else level.add(0,tmp.val);
                if(tmp.left!=null) queue.add(tmp.left);
                if(tmp.right!=null) queue.add(tmp.right);
            }
            res.add(level);
            order = !order;
        }
        return res;
    }
}
posted @ 2020-04-29 11:09  AAAmsl  阅读(68)  评论(0编辑  收藏  举报