我正在尝试创建一种返回字符串的链表的方法.有一棵树,树中的每个节点都存储一个字符.该方法应该找到通过树的所有可能路径.每个路径都会创建一个字符串,并将其添加到列表中.
在第二个for循环中似乎有一个我无法解决的问题.该方法仅返回在第一个if语句中添加的字符.
每个节点都包含变量childList(这是子节点的链接列表)和nodevalue(其是节点存储的字符).
public LinkedList findStrings() {
LinkedList paths = new LinkedList();
//add character to list if there are no children
if (childList.isEmpty()){
paths.add("" + nodevalue);
return paths;
}
//use recursion to add paths from all children to the list
for (TreeNode t : childList){
paths.addAll(t.findStrings());
//add nodevalue to the beginning of all strings in the list
for (String s : paths){
s = nodevalue + s;
}
}
for (String s : paths) System.out.println(s); //for debugging
return paths;
}
解决方法:
在内部循环中更改s时,您只是在重新分配变量s,而不是重新