我正在尝试创建一个返回字符串链接列表的方法。有一棵树,树中的每个节点都存储一个字符。该方法应该找到通过树的所有可能路径。每个路径创建一个字符串,该字符串被添加到列表中。
在第二个 for 循环中似乎存在我无法弄清楚的问题。该方法仅返回在第一个 if 语句中添加的字符。
每个节点包含变量 childList,它是子节点的链表,和 nodevalue,它是节点存储的字符。
public LinkedList<String> findStrings() {
LinkedList<String> paths = new LinkedList<String>();
//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;
}