【发布时间】: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