Sorry in advance for any English error that I may commit. I have a school project for university and I have to use a trie to index words and have multiple functions to do multiple things. I'm programming in C. I have done a recursive function to find the biggest word in the trie and it is working. Here's the function:
int BiggestWord(ELEMENT *P)
{
if (!P) return -1;
int Alt_max = 0;
for (int i = 0; i < MAX_VECTOR; i++)
Alt_max = Biggest(BiggestWord(P->V[i]), Alt_max);
return 1 + Alt_max;
}
'Biggest' is just a function that returns the biggest value between two values.
Now for the smallest word function. I was thinking about how to do it and tried to do check when the word ended looking for 'NULL' after every Element. Here is my attempt:
int SmallestWord(ELEMENT *P)
{
if (!P) return -1;
int Alt_min = 1;
for (int i = 0; i < MAX_VECTOR; i++)
{
if(P->V[i] != NULL)
{
SmallestWord(P->V[i]);
Alt_min++;
}
}
return Alt_min;
}
I can't find a way to make it work. I also thought about trying to, after every word, point that there's the end of a word, and then try to go through every branch of the trie and find the smallest word. It's my first half-year coding and I'm finding some difficulties trying to learn it. If anyone could help me by giving me hints or trying to give me clues of where to go I would appreciate it very much since this is a very important project I must finish and do well.
Also, my data structures are the following:
#define MAX_VECTOR 26
// 26 letters of the Alphabet I'm using
typedef struct ELEMENT
{
int occurrences_word; // this is used for counting number of occurrences of a word
struct ELEMENT *V[MAX_VECTOR];
} ELEMENT;
typedef struct TRIE
{
ELEMENT *root_trie;
int num_words;
} TRIE;
Thank you in advance to everyone that contributes to helping me out Regards
I see no elegant way to do it. The problem is that a -1
which means a null pointer must be treated differently from a low number which means a short word.
Her is a crude but workable solution:
int SmallestWord(ELEMENT *P)
{
if (!P) return -1;
if(P->occurrences_word != 0) // this is the end of a word
return 1;
int Alt_min = -1;
for (int i = 0; i < MAX_VECTOR; i++)
{
int n = SmallestWord(P->V[i]);
if(n!=-1)
if(n<Alt_min || Alt_min == -1)
Alt_min = n;
}
return 1 + Alt_min;
}