我找到了一个遍历所有trie的函数,并返回一个包含我的trie中存在的所有单词的列表。我的问题是我无法为我工作,任何帮助都会受到赞赏。
class Node {
public:
Node();
Node* ch[26];
bool isEnd;
};
Node::Node() {
for(int i = 0; i < 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 i = 0; i < 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 i = 0; i < 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;
}
测试主要:
int main() {
Trie T;
string word;
for(int i = 0; i < 10; i++) {
cin >> word;
insert(word, root);
}
system("PAUSE");
return 0;
}