[英]Why does my method print an empty list?
我正在尝试在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
。
谢谢。
将相同的ArrayList
实例(由temp
变量引用)多次添加到reuslt
列表中是错误的,因为最后result
将包含多个空列表(或更准确地说,是对同一空列表的多个引用)。
您应该在每次迭代中创建一个新实例,而不是通过temp
清除单个实例引用:
while(true){
levelCount = q.size();
if(levelCount == 0) break;
ArrayList<Integer> temp = new ArrayList<Integer>();
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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.