Redian新闻
>
Recusion is fucking magic!!
avatar
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; iTrieNode 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.
avatar
J*r
2
当年我刚学到recursion的时候也曾发出类似的感慨,:)
avatar
s*e
3
Haha...
you are fxxcking right if and only if you need that magic.
Do not go to extreme. It has its own problem.
相关阅读
logo
联系我们隐私协议©2024 redian.news
Redian新闻
Redian.news刊载任何文章,不代表同意其说法或描述,仅为提供更多信息,也不构成任何建议。文章信息的合法性及真实性由其作者负责,与Redian.news及其运营公司无关。欢迎投稿,如发现稿件侵权,或作者不愿在本网发表文章,请版权拥有者通知本网处理。