Java 为什么我的方法打印空列表?

Java 为什么我的方法打印空列表?,java,algorithm,arraylist,binary-tree,Java,Algorithm,Arraylist,Binary Tree,我试图在ArrayList结果中逐级打印树。结果中的每个列表都被视为自己的级别 例如: 1 / \ 2 3 / \ / \ 4 5 6 7 ==> [1][2, 3][4, 5, 6, 7] 由于某种原因,我一直收到一张空名单。这是我的密码: public ArrayList<ArrayList<Integer&

我试图在ArrayList结果中逐级打印树。结果中的每个列表都被视为自己的级别

例如:

         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变量引用的同一ArrayList实例多次添加到您的REUSELT列表中是错误的,因为您的结果将包含多个空列表,或者更准确地说,在末尾包含对同一空列表的多个引用

您应该在每次迭代中创建一个新实例,而不是通过temp清除单个实例引用:


是的,临时清除是有问题的。尝试替换result.addtemp;使用result.addnew ArrayListtemp@它成功了,谢谢。顺便说一句,我很好奇,如果我在添加到结果列表后清除temp,为什么会得到一个空列表。temp中的所有内容不应该在清除之前添加到结果中吗?它确实添加到结果中,然后被清除。。。您没有向结果中添加数字列表-您正在添加临时值。所以,如果你清除了temp,你就清除了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);
}