【问题标题】:Weird bug during recursion递归期间的奇怪错误
【发布时间】:2021-03-09 19:29:07
【问题描述】:

我有以下代码构建一棵二叉树,其中所有节点都是 0 或 1,因此从根到叶的每条路径都是一定长度的二进制字符串。最初,我的代码只是打印所有路径(路径是整数列表,即 [0, 0, 0, 1, 0, 1])。现在我正在尝试将所有路径实际保存在列表列表中,但我得到了意外的输出。以下是相关代码:

public class Tree{
  Node root;
  int levels;
  LinkedList<LinkedList<Integer>> all;

  Tree(int v){
    root = new Node(v);
    levels = 1;
    all = new LinkedList<LinkedList<Integer>>();
  }

  public static void main(String[] args){
    Tree tree = new Tree(0);
    populate(tree, tree.root, tree.levels);
    tree.printPaths(tree.root);  // this is the part that prints the paths one by one
    for (LinkedList<Integer> l: tree.all){ // this is when i later tried to save all paths to the
      System.out.println(l);               // list all and then print them out from that list
    }
  }

  
   public void printPaths(Node node)
   {
       LinkedList<Integer> path = new LinkedList<Integer>();
       printPathsRecur(node, path, 0);
   }

  void printPathsRecur(Node node, LinkedList<Integer> path, int pathLen)
    {
        if (node == null)
            return;

        // append this node to the path array
        path.add(node.value);
        path.set(pathLen, node.value);
        pathLen++;

        // it's a leaf, so print the path that led to here
        if (node.left == null && node.right == null){
            printArray(path, pathLen); // Initial version which prints the paths one by one - WORKS FINE
            all.add(path);  // This is when I try to actually keep the paths in a list - doesn't work
        }
        else
        {
            printPathsRecur(node.left, path, pathLen);
            printPathsRecur(node.right, path, pathLen);
        }
    }
...}

基本上,当我只是一张一张地打印它们而不保存它们时,我得到了预期的输出:

...
0 1 0 0 1 0
0 1 0 0 1 1
0 1 0 1 0 0
0 1 0 1 0 1
...

但是当我尝试将路径保存到列表列表并打印该列表的每个元素时,我得到了:

[0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1]
[0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1]
...

看起来列表只是一次又一次地保存相同的超长条目。

【问题讨论】:

  • 看起来您将所有内容都写在同一个列表中。阅读 Java 中的深度复制。我建议使用调试器,它是一个非常方便的工具,可以帮助您更好地了解您的代码是如何工作的,以及它在哪些地方没有按照您的计划进行操作。

标签: java recursion linked-list tree


【解决方案1】:

我无法运行您发布的代码,因为它不完整。发布SSCCE 和一些下次表现出“奇怪”行为的特定测试数据可能是个好主意。

但据我所知,我猜问题出在您在 printPathsRecur 方法中传递 LinkedList&lt;Integer&gt; path 参数的方式上。

您正在printPaths() 方法中创建路径 链表。然后你将它的引用传递给printPathsRecur() 方法。它会修改列表,然后递归地运行自己两次,将相同的引用传递给您在 printPaths() 方法中创建的原始 path 链接列表。这意味着 printPathsRecur() 方法的所有递归调用实际上都在使用它只是不断添加的相同列表,在 all 2D 链接列表中创建一个长列表。只是对同一个链表的许多引用。

【讨论】:

    猜你喜欢
    • 2020-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-22
    相关资源
    最近更新 更多