c++ - get all words exist in trie using recursion -
i found function traverse trie , return list contains words exist in trie. problem can't make work me, appreciated.
class node { public: node(); node* ch[26]; bool isend; }; node::node() { for(int = 0; < 26; i++) ch[i] = null; isend = 0; } class trie { public: node* root; trie() {root = new node();} void insert(string word, node* ptr); bool find(string word, node* ptr); list<string> findwords(node* root); }; void trie::insert(string word, node* ptr) { for(unsigned int = 0; < word.size(); i++) { if(ptr->ch[word[i]-'a'] == null) ptr->ch[word[i]-'a'] = new node(); ptr = ptr->ch[word[i]-'a']; } ptr->isend = 1; } list<string> trie::findwords(node* ptr) { list<string> result; if(ptr->isend) result.push_back(""); for(int = 0; < 26; i++) if(ptr->ch[i] != null) { ptr = ptr->ch[i]; list<string> childresult = findwords(ptr); char letter = (char) (97 + i); for(string sufix : childresult) result.push_back("" + letter + sufix); } copy(result.begin(),result.end(),ostream_iterator<string> (cout," ")); return result; }
test main:
int main() { trie t; string word; for(int = 0; < 10; i++) { cin >> word; insert(word, root); } system("pause"); return 0; }
Comments
Post a Comment