I have a specific question regarding the Trie data structure and what is going wrong with my code. Function parameter root always is NULL when I recursively call insert. Here is my code:
Code:
//subNodes is an array of TrieNode pointers that contains indices for all letters in the alphabet
bool insert(const string& word, TrieNode* root, int curI = 0)
//PRE: word must be a valid word in a dictionary
//POST: True when a word is inserted into the Trie, false otherwise
{
if(curI >= word.length()) //word has been scanned fully
{
root->isWord = true;
return true;
}
else //word has more letters to be scanned
{
if(root->subNodes[word[curI] - 'A'] == NULL) //if the current letter of the word is not in the trie
{ // insert the letter and advance the current letter of the word
root->subNodes[word[curI] - 'A'] = new TrieNode(word[curI]);
insert(word, root->subNodes[word[curI] - 'A'], curI++);
}
else //if the currrent letter of the word is in the trie
{ // advance the current letter of the word
insert(word, root->subNodes[word[curI] - 'A'], curI++);
}
}
}
I tested this by replacing subNodes[word[curI] - 'A'] with subNodes[word[13]] (13 is the index for N in the alphabet and I was testing the word not) and root was no longer NULL for that call. Therefore something is going wrong with the indexing. Does anyone know what is wrong? I considered using a C++ map or vector. Does anybody have any disagreements with using an array?
Did you mean
++curl– i.e. pass in the incremented value to the recursion call? As it stands you’re passing the same value into each recursion sincecurl++is post-increment. It may be easier to just writecurl + 1anyway since you don’t need the curl value again.