为什么我的方法打印一个空列表?
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);
}
我正在尝试在 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);
}