I’m trying to put all words in a trie in a string, a word is denoted by the eow field being true for a certain character in the trie data structure, hence a trie can could have letters than lead up to no word, for ex “abc” is in the trie but “c”‘s eow field is false so “abc” is not a word
Here is my Data structure
struct Trie {
bool eow; //when a Trie field isWord = true, hence there is a word
char letter;
Trie *letters[27];
};
and here is my attemped print-all function, basically trying to return all words in one string seperated by spaces for words
string printAll( string word, Trie& data)
{
if (data.eow == 1)
return word + " ";
for (int i = 0; i < 26; i++) {
if (data.letters[i] != NULL)
printAll( word + data.letters[i]->letter, *(data.letters[i]));
}
return "";
}
Its not outputting what i want, any suggestions?
You’re not using the return value of your recursive
printAll()call, so all the sub-words you generate are lost. Try something like this:For what it’s worth, this is a bit inefficient in that it allocates lots of temporary strings. Each recursive call has its own
wordsstring which is built up, returned, and destroyed. It’d be better to add all the words to one string.Also you might consider using a vector of words rather than adding them together with spaces. That way you can more easily iterate over each word.
Then to call it: