2 回答
TA贡献1798条经验 获得超3个赞
问题是您没有对递归调用返回的值做任何事情。您需要将它们实际添加到列表中:
list.addAll(getAllWordsHelpers(current.getLeftChild()));
list.add(current.getWord();
list.addAll(getAllWordsHelpers(current.getRightChild()));
一种更有效的方法是将列表传递给方法,这样您就不需要继续创建新列表:
private void getAllWordHelpers(List<String> list, DictionaryWord current) {
if (current != null) {
getAllWordHelpers(list, current.getLeftChild());
list.add(current.getWord());
getAllWordHelpers(list, current.getRightChild());
}
}
TA贡献1846条经验 获得超7个赞
The problem is you want to store words across multiple call stacks during inorder traversal, which is possible only by using a global object which should be available to all call stacks during recursive calls.
So here we have used a formal argument called words which represent a list object and this object will be common to all call stacks during recursive calls.
ArrayList<String> words = getAllWordsHelper(current, null)
private static ArrayList<String> getAllWordsHelper(DictionaryWord current, List<String> words) {
if(words == null) words = new ArrayList();
if (current != null) {
getAllWordsHelper(words, current.getLeftChild());
list.add(current.getWord());
getAllWordsHelper(words, current.getRightChild());
}
return words;
}
}
添加回答
举报