【问题标题】:Why does my method print an empty list?为什么我的方法打印一个空列表?
【发布时间】: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


【解决方案1】:

将相同的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);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-05-05
    • 2015-05-22
    • 2020-12-15
    • 2013-07-23
    • 1970-01-01
    • 1970-01-01
    • 2020-11-10
    • 2014-12-16
    相关资源
    最近更新 更多