【发布时间】:2021-08-22 10:18:23
【问题描述】:
我试图在List<List<Integer>> 中添加一些子列表一次。但问题是,它会被多次添加。
这是代码:
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;
}
}
}
请帮帮我。
提前致谢。
P.S:我认为这是一个愚蠢的错误 somwehere 或一个错误。
【问题讨论】:
-
这看起来像是一个问题,最好通过使用调试器单步执行代码来查看添加的内容。当你这样做时会发生什么?
-
你能解释一下其他部分在做什么吗?
-
在其他方面,我正在尝试获取现有列表并添加级别的元素基础。
标签: java binary-tree breadth-first-search