title: Java - Values are added multiple times in a list
body: <p>I'm trying to add some sub lists in a <code>List&lt;List&lt;Integer&gt;&gt;</code> once. But the problem is, it's getting added multiple times.</p>
  <p>This is the code:</p>
  <pre><code>class Solution {
      public List&lt;List&lt;Integer&gt;&gt; zigzagLevelOrder(TreeNode root) {
          if(root == null) return null;
          
          List&lt;List&lt;Integer&gt;&gt; res = new ArrayList&lt;&gt;();
          Queue&lt;Pair&gt; q = new LinkedList&lt;&gt;();
          
          q.add(new Pair(root, 0));
          
          while(!q.isEmpty()) {
            Pair tmp = q.poll();
            int data = tmp.root.val;
            int level = tmp.level;
            
            List&lt;Integer&gt; list;
            // get number of sublists in res
            if(res.size() == level) {
              list = new ArrayList&lt;&gt;();
              list.add(data);
            }
            
            else {
              list = res.get(level);
              System.out.println(&quot;existing list = &quot; + list);
              if(level % 2 == 0) {
                list.add(data);
              }
              else list.add(0, data);
            }
            // By now, the sublists are populated
            
            System.out.println(&quot;list = &quot; + list);
            // this shows the correct ans
            
            res.add(list);
            // this shows duplicated sublist
  
            System.out.println(&quot;res = &quot; + res);
            
            if(tmp.root.left != null) q.add(new Pair(tmp.root.left, level + 1));
            if(tmp.root.right != null) q.add(new Pair(tmp.root.right, level + 1));
          }
        
        return res;
      }
    
      class Pair {
        TreeNode root;
        int level;
        
        Pair(TreeNode root, int level) {
          this.root = root;
          this.level = level;
        }
      }
  }
  </code></pre>
  <p>Please help me on this.</p>
  <p>Thanks in advance.</p>
  <p>P.S: I think it's a silly mistake somwehere or a blunder.</p>