2ms java solution,easy and no reverse


  • 1
    L
    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
         List<List<Integer>> res = new LinkedList<>();  
         if(root == null) return res;
         Queue<TreeNode> queue = new LinkedList<>();
         queue.add(root);
         int size1 = 0, size2 = 0;
         while(!queue.isEmpty()){
              size1 = queue.size();
              size2 = res.size();
              List<Integer> list = new LinkedList<>();
              for(int i = 0; i < size1; i++){
                  TreeNode node = queue.remove();
                  if(size2 % 2 == 0){
                      list.add(node.val);
                  }else{
                      list.add(0,node.val);
                  }
                  if(node.left != null){
                      queue.add(node.left);
                  }
                  if(node.right != null){
                      queue.add(node.right);
                  }
              }
               res.add(list);
    
         }
         return res;
         
    }

Log in to reply
 

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