My accepted java solution


  • 0
    D
        public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
            Queue<TreeNode> q = new ArrayDeque<TreeNode>();
            List<List<Integer>> levelOrder = new ArrayList<List<Integer>>();
            List<Integer> eachLevel;
            if(root == null) {
                return levelOrder;
            }
            q.add(root);
            boolean flag = false;
            while(!q.isEmpty()) {
                eachLevel = new ArrayList<Integer>();
                int size = q.size();
                for(int i = 0; i < size;i++) {
                    if(q.peek().left != null) q.add(q.peek().left);
                    if(q.peek().right != null) q.add(q.peek().right);
                    if(flag) {
                        eachLevel.add(0,q.poll().val); 
                    }
                    else {
                        eachLevel.add(q.poll().val);
                    }
                }
                flag = !flag;  
                levelOrder.add(eachLevel);
            }
            return levelOrder;
        }
    }

Log in to reply
 

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