Almost done with printing this trie out. But running into a little of trouble. I currently have:
void printSubtree(struct trie *subtree, char word[100], int level) {
int i;
if (subtree == NULL){
return;
}
if (subtree->wordEnd) {
word[level] =0;
printf( "%s \n ", word);
}
for (i = 0; i<26;i++) {
if (subtree->children[i]!= NULL) {
word[level] = 97 + i;
level++;
printSubtree( subtree->children[i], word, level);
}
}
}
When I do this, it skips the first letter, so I have another that includes this snippet which prints the first letter, then calls printSubtree to print the rest of the letters for that corresponding first letter.
for (i = 0; i<26;i++) {
if (temp->children[i]!= NULL) {
arr[0] = temp->children[i]->letter;
printSubtree(temp->children[i], arr, 1);
}
}
What happens though is that it doesn't print the trie out correctly. For example, if "bro" and "brim" are in my trie, this prints out "bro" then "brio", instead of brim.
Thanks in advance.
To my understanding, if the recursion is performed in the part
for (i = 0; i < 26; i++)
{
if (subtree->children[i] != NULL)
{
word[level] = 97 + i;
level++;
printSubtree(subtree->children[i], word, level);
}
}
the variable level
is increased, but never decreased, which means that it accumulates for every child. The following change should work as desired.
for (i = 0; i < 26; i++)
{
if (subtree->children[i] != NULL)
{
word[level] = 97 + i;
// increment level for the recursive calls
printSubtree(subtree->children[i], word, level + 1);
}
}