typedef struct TrieNode {
char c;
struct TrieNode* children[26];
int isEndOfWord;
} TrieNode;
TrieNode* createNode(char c) {
TrieNode* node = (TrieNode*)malloc(sizeof(TrieNode));
node->c = c;
node->isEndOfWord = 0;
for (int i = 0; i < 26; i++) node->children[i] = NULL;
return node;
}
void insert(TrieNode* root, const char* word) {
TrieNode* current = root;
while (*word) {
int index = *word - 'a';
if (!current->children[index]) {
current->children[index] = createNode(*word);
}
current = current->children[index];
word++;
}
current->isEndOfWord = 1;
}
void printTrie(TrieNode* root, int level) {
if (!root) return;
for (int i = 0; i < 26; i++) {
if (root->children[i]) {
for (int j = 0; j < level; j++) printf(" ");
printf("%c%s\n", root->children[i]->c, root->children[i]->isEndOfWord ? "*" : "");
printTrie(root->children[i], level + 1);
}
}
}
int main() {
TrieNode* root = createNode(' ');
insert(root, "cat");
insert(root, "car");
insert(root, "dog");
printTrie(root, 0);
return 0;
}The Trie inserts words character by character. The '*' marks the end of a word. Both "cat" and "car" share 'c' and 'a'. The nodes 't' and 'r' are ends of words, so they have '*'. Similarly, "dog" is separate with 'd' -> 'o' -> 'g*'.
Words share prefix 'ba'. The nodes are: b, a, t, l, l, d. Total nodes excluding root = 6.
The loop runs from i = 0 to i <= strlen(word), so it accesses word[strlen(word)] which is the null character '\0'. Subtracting 'a' from '\0' gives a negative index, causing invalid memory access and segmentation fault.
/* Assume same TrieNode and printTrie as in c1 */ int main() { TrieNode* root = createNode(' '); insert(root, "to"); insert(root, "tea"); insert(root, "ted"); insert(root, "ten"); printTrie(root, 0); return 0; }
Words inserted: "to" ends at 'o*', "tea", "ted", "ten" share prefix 'te' with ends at 'a*', 'd*', 'n*'. The root 't' is not end of word.
If no words share prefixes, each word adds M new nodes. So total nodes = N * M.
