Search code examples
c++dictionarydata-structurestrie

C++ Depth First Search of Trie with prefix parameter


I'm trying to implement a trie that can print out the frequency of words with a given prefix.

Edit: Thanks to @kaidul-islam finding my error with the following error:

new_word->child[letter]->prefixes_++;

Below is the fixed code:

Trie Class:

class Trie
{
public:
    Trie(): prefixes_(0), is_leaf_(false), frequency_(0)
    {
        for (int i=0; i<26; i++)
        {
            child[i] = nullptr;
        }
    }
    virtual ~Trie();

    //Child nodes of characters from a-z
    Trie *child[26];
    //vector<Trie> child;

    int prefixes_;

    //accessor & mutator functions
    bool GetIsLeaf() { return is_leaf_; }
    void SetIsLeaf(bool val) { is_leaf_ = val; }
    int GetFrequency() { return frequency_; }
    void SetFrequency(int val) { frequency_ = val; }
    int GetPrefixes() { return prefixes_; }
    void SetPrefixes(int val) { prefixes_ = val; }
    bool is_leaf_;

private:
    //bool is_leaf_;
    int frequency_;
};

Function in Question:

void AddWord(string &word, Trie *root)
{
    Trie *new_word = root;
    new_word->prefixes_++;
    for(unsigned int i = 0 ; i < word.length(); i++)
    {
        int letter = (int)word[i] - (int)'a';   //extract character of word
        if(new_word->child[letter] == nullptr)
        {
            new_word->child[letter] = new Trie;
        }

        /*cout << "not value of x: " << new_word->child[letter]->GetPrefixes() << endl;
        int x = (new_word->child[letter]->GetPrefixes())+1;
        cout << "value of x: " << x << endl;
        new_word->child[letter]->SetPrefixes(x);*/
        new_word->child[letter]->prefixes_++;

        new_word = new_word->child[letter];
    }
    new_word->SetFrequency(new_word->GetFrequency()+1);
    /*
    cout << "Word: " << word << endl;
    cout << "frequency: " << new_word->GetFrequency() << endl;
    cout << "prefixes: " << new_word->GetPrefixes() << endl;
    cout << "is leaf: " << new_word->GetIsLeaf() << endl << endl;
    */
}

Solution

  • After a quick inspection, I found you didn't initialize member variables in your constructor.

    Trie(): prefixes_(0),
            is_leaf_(false),
            frequency_(0) {
    
        for(int i = 0; i < 26; i++) {
            child[i] = nullptr;
        }
    }
    

    Unlike global variable, there is no guarantee that prefixes_ will be 0 by default on declaration. And child[i] is not guaranteed to be nullptr too. You need to initialize everything.