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