concise java solution


  • 0
    J
        public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
            List<List<Integer>> res = new ArrayList<List<Integer>>();
            if(root == null) return res;
            Queue<TreeNode> q = new LinkedList<TreeNode>();
            q.offer(root);
            while(!q.isEmpty()){
                int size = q.size();
                List<Integer> each = new ArrayList<Integer>();
                for(int i = 0; i < size; i++){
                    TreeNode temp = q.poll();
                    if(temp.left != null) q.offer(temp.left);
                    if(temp.right != null) q.offer(temp.right);
                    each.add(temp.val);
                }
                res.add(each);
            }
            int len = res.size();
            for(int i = 0; i < len; i++){
                if(i%2!=0) {
                    List<Integer> layer = res.get(i);
                    Collections.reverse(layer);
                    res.set(i,layer);
                }
            }
            return res;
        }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.