尝试TRIE DS实施

时间:2017-11-21 17:27:35

标签: data-structures trie

所以,我试图实现TRIE DS,而树中的节点获取addWord结束后分配的Words值,但是当我遍历树时,打印的值为零。我做错了什么,无法指出。请有人帮忙。

    #include<iostream>
    #include<string>

    using namespace std;

    struct trie{
        int words;
        int prefixes;
        trie* edges[26];
    };

    void addWord(trie* vertex, string word){

        if(word.length() == 0){
            vertex->words = vertex->words + 1;
        }
        else{
            // cout<<word<<endl;
            vertex->prefixes = vertex->prefixes + 1;
            char k = word[0];
            if(vertex->edges[k - 'a'] == NULL){
                trie *n = (trie*)malloc(sizeof(trie));
                n->words = 0;
                n->prefixes = 0;
                for(int i=0;i<26;i++)
                    vertex->edges[i] = NULL;
                vertex->edges[k - 'a'] = n;
            }
            word.erase(0, 1);
            addWord(vertex->edges[k - 'a'], word);
        }
    };
    void traverse(trie *vertex){
        if(vertex != NULL){
            for(int i=0;i<26;i++){
                if(vertex->edges[i] != NULL){
                    traverse(vertex->edges[i]);
                    cout<<char(i+'a')<<" - "<<vertex->prefixes<< " : "<<vertex->words<<endl;
                }
            }
        }

    };


    int main(){
        string word = "hello";
        trie* head = (trie*)malloc(sizeof(trie));
        for(int i=0;i<26;i++)
            head->edges[i] = NULL;
        head->words = 0;
        head->prefixes = 0;
        addWord(head, word);
        string s = "lo";
        traverse(head);
        return 0;
    }

1 个答案:

答案 0 :(得分:1)

代码存在两个问题:

  1. addWord功能块else块内,for循环中,将vertex->edges[i] = NULL;更改为n->edges[i] = NULL;
  2. 您要求的问题出在traverse功能中。您没有为最后words所指示的节点打印o计数,而是为具有o边缘的节点打印它。所以改变一下:

    cout<<char(i+'a')<<" - "<<vertex->prefixes<< " : "<<vertex->words<<endl;

  3. 到此:

    cout<<char(i+'a')<<" - "<<vertex->edges[i]->prefixes<< " : "<<vertex->edges[i]->words<<endl;