【发布时间】:2018-02-11 06:24:11
【问题描述】:
我正在尝试在ArrayList<ArrayList<Integer>> result 中逐级打印树。 result 中的每个列表都被视为自己的级别。
例子:
1
/ \
2 3
/ \ / \
4 5 6 7
==> [1][2, 3][4, 5, 6, 7]
由于某种原因,我不断返回一个空列表。这是我的代码:
public ArrayList<ArrayList<Integer>> printLevelByLevel(TreeNode root) {
ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
ArrayList<Integer> temp = new ArrayList<Integer>();
if(root == null) return result;
int levelCount = 0;
Queue<TreeNode> q = new LinkedList<TreeNode>();
q.add(root);
while(true){
levelCount = q.size();
if(levelCount == 0) break;
while(levelCount > 0){
TreeNode curr = q.poll();
temp.add(curr.data);
if(curr.left != null){
q.add(curr.left);
}
if(curr.right != null){
q.add(curr.right);
}
levelCount--;
} // end of inner while
result.add(temp);
temp.clear();
} // end of outter while loop
return result;
}
我的 temp.clear() 对吗?我试着把它放在不同的地方,但结果还是一样。我知道我可以用两个Queues 做到这一点,但我希望能够用一个Queue 做到这一点。
谢谢。
【问题讨论】:
-
是的, temp.clear() 有问题。尝试替换“result.add(temp);”用“result.add(new ArrayList(temp));”
-
@Ran 成功了,谢谢。顺便说一句,我很好奇如果我在添加到结果列表后清除 temp,为什么我会得到一个空列表。不应该在清除之前将 temp 中的所有内容添加到结果中吗?
-
它确实被添加到了结果中,然后被清除了......您没有在结果中添加数字列表 - 您正在添加 temp.所以如果你清除温度,你就会清除结果。因此,您需要根据温度生成一个新列表。
标签: java algorithm arraylist binary-tree