Complete the code to initialize the root node of a Trie.
struct TrieNode* root = malloc(sizeof(struct TrieNode));
root->isEndOfWord = [1];The root node's isEndOfWord should be set to 0 because it does not represent the end of any word initially.
Complete the code to check if a character exists as a child in the Trie node.
if (node->children[[1]] != NULL) { // character exists }
We use c - 'a' to convert the character c to an index between 0 and 25 for the children array.
Fix the error in the function that inserts a word into the Trie by completing the blank.
void insert(struct TrieNode* root, const char* word) {
struct TrieNode* node = root;
for (int i = 0; word[i] != '\0'; i++) {
int index = word[i] - 'a';
if (node->children[index] == NULL) {
node->children[index] = malloc(sizeof(struct TrieNode));
memset(node->children[index], 0, sizeof(struct TrieNode));
}
node = node->children[[1]];
}
node->isEndOfWord = 1;
}The variable index holds the correct child index for the current character, so we use it to move to the next node.
Fill in the blank to create a hash map lookup for prefix matching.
int prefix_exists(const char* prefix, HashMap* map) {
int length = strlen(prefix);
for (int i = 0; i < length; i++) {
if (hash_map_get(map, prefix[[1]]) == NULL) {
return 0;
}
}
return 1;
}The loop variable i is used to access each character in the prefix. The hash map key is the character at prefix[i].
Fill all three blanks to build a Trie node and insert a word.
struct TrieNode* create_node() {
struct TrieNode* node = malloc(sizeof(struct TrieNode));
for (int i = 0; i < [1]; i++) {
node->children[i] = [2];
}
node->isEndOfWord = [3];
return node;
}
void insert_word(struct TrieNode* root, const char* word) {
struct TrieNode* node = root;
for (int i = 0; word[i] != '\0'; i++) {
int index = word[i] - 'a';
if (node->children[index] == NULL) {
node->children[index] = create_node();
}
node = node->children[index];
}
node->isEndOfWord = 1;
}We initialize 26 children for each letter of the alphabet, set each child pointer to NULL, and mark isEndOfWord as 0 initially.
