Recusion is fucking magic!!# Java - 爪哇娇娃
l*0
1 楼
public List listAllWordsinTrie(){
List words = new ArrayList();
if(root == null){
return words;
}
StringBuilder prefix = new StringBuilder();
allWordsHelper(root.children,prefix,words);
return words;
}
// depth first search
private void allWordsHelper(List children, StringBuilder
prefix, List words){
for(int i= 0; i TrieNode child = children.get(i);
if(!child.isWord_){
prefix.append(child.data_);
allWordsHelper(child.children, prefix, words);
}else{
prefix.append(child.data_);
words.add(prefix.toString());
}
prefix.deleteCharAt(prefix.length()-1);
}
}
It took me a while to figure out the last line, "prefix.deleteCharAt(prefix.
length()-1)".
Recursion is hard, magical, but in the end it often turns out to be
beautiful.
List
if(root == null){
return words;
}
StringBuilder prefix = new StringBuilder();
allWordsHelper(root.children,prefix,words);
return words;
}
// depth first search
private void allWordsHelper(List
prefix, List
for(int i= 0; i
if(!child.isWord_){
prefix.append(child.data_);
allWordsHelper(child.children, prefix, words);
}else{
prefix.append(child.data_);
words.add(prefix.toString());
}
prefix.deleteCharAt(prefix.length()-1);
}
}
It took me a while to figure out the last line, "prefix.deleteCharAt(prefix.
length()-1)".
Recursion is hard, magical, but in the end it often turns out to be
beautiful.