Java Iteration Solution Using addFirst : )


  • 1
    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
            
            List<List<Integer>> list = new LinkedList<>();
            if(root == null) return list;
            
            LinkedList<TreeNode> queue = new LinkedList<>();
            int level = 1;
            queue.offer(root);
            
            while(!queue.isEmpty()){
                
                int levelNum = queue.size();
                
                LinkedList<Integer> temp = new LinkedList<>();
             
                for(int i = 0; i < levelNum; i++){
                    
                    TreeNode node = queue.poll();
                    if(level % 2 == 1){
                        temp.add(node.val);
                    }
                    else{
                        temp.addFirst(node.val);
                    }
       
                    if(node.left != null)
                        queue.offer(node.left);
                    if(node.right != null)
                        queue.offer(node.right);
                }
                list.add(temp);
                level++;
            }
            return list;
        }
    

Log in to reply
 

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