1

我找到了一个函数,它遍历所有的 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;
}
4

0 回答 0