typedef struct TrieNode { // number of times this string occurs in the corpus in
ID: 3712551 • Letter: T
Question
typedef struct TrieNode
{
// number of times this string occurs in the corpus
int count;
// 26 TrieNode pointers, one for each letter of the alphabet
struct TrieNode *children[26];
// the co-occurrence subtrie for this string
struct TrieNode *subtrie;
} TrieNode;
Explanation / Answer
Below is your code: -
// for this function make a comparison to the empty string
// if it is empty then call a function that returns the total number
// of words that exist in the trie. the function definition for that is this
int findTotalWords(TrieNode *root, int *count) {
int i;
if(root == NULL)
return 0;
if(root->count > 1 || root->count == 1)
return *count = *count + root->count;
for(i = 0; i < 26; i++)
findTotalWords(root->children[i], count);
return *count;
}
// this fxn is called by prefixCount to get to the terminal node
// of the given string
TrieNode *findNode(TrieNode *root, char *str) {
int i, index, len = strlen(str);
if(root == NULL)
return NULL;
for(i = 0; i < len; i++) {
// printf("%c ", str[i]);
index = tolower(str[i]) - 'a';
// printf("index: %d ", index);
if(root->children[index] == NULL)
return NULL;
root = root->children[index];
}
return root;
}
// helper fxn called by prefixCount that does all the recursive work
int prefixCountHelper(TrieNode *node, int *count) {
int i;
if(node == NULL)
return 0;
if(node->count > 1 || node->count == 1)
*count += node->count;
for(i = 0; i < 26; i++) {
prefixCountHelper(node->children[i], count);
}
return *count;
}
// counts the number of words that contain the given prefix
int prefixCount(TrieNode *root, char *str){
int count = 0;
if(root == NULL)
return 0;
if(str == NULL)
return 0;
if(strcmp(str, "") == 0)
return count = findTotalWords(root, &count);
TrieNode *temp = findNode(root, str);
count = prefixCountHelper(temp, &count);
return count;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.