2 回答

TA貢獻(xiàn)1798條經(jīng)驗(yàn) 獲得超3個(gè)贊
問(wèn)題是您沒(méi)有對(duì)遞歸調(diào)用返回的值做任何事情。您需要將它們實(shí)際添加到列表中:
list.addAll(getAllWordsHelpers(current.getLeftChild()));
list.add(current.getWord();
list.addAll(getAllWordsHelpers(current.getRightChild()));
一種更有效的方法是將列表傳遞給方法,這樣您就不需要繼續(xù)創(chuàng)建新列表:
private void getAllWordHelpers(List<String> list, DictionaryWord current) {
if (current != null) {
getAllWordHelpers(list, current.getLeftChild());
list.add(current.getWord());
getAllWordHelpers(list, current.getRightChild());
}
}

TA貢獻(xiàn)1846條經(jīng)驗(yàn) 獲得超7個(gè)贊
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;
}
}
添加回答
舉報(bào)