struct TrieNode {
bool isEndOfWord;
TrieNode* children[26];
TrieNode() {
isEndOfWord = false;
for (int i = 0; i < 26; i++) {
children[i] = nullptr;
}
}
};
#include <iostream>
int main() {
TrieNode node;
std::cout << node.isEndOfWord << " ";
int count = 0;
for (int i = 0; i < 26; i++) {
if (node.children[i] == nullptr) count++;
}
std::cout << count << std::endl;
return 0;
}The constructor sets isEndOfWord to false (which prints as 0) and initializes all 26 children pointers to nullptr. Counting the null pointers gives 26.
The children array holds pointers to child nodes for each character (usually 26 for lowercase English letters). This allows branching to next letters in stored words.
struct TrieNode {
bool isEndOfWord;
TrieNode* children[26];
TrieNode() {
isEndOfWord = false;
for (int i = 0; i <= 26; i++) {
children[i] = nullptr;
}
}
};The loop uses i <= 26 which accesses index 26, but valid indices are 0 to 25. This causes out-of-bounds access leading to runtime error.
struct TrieNode {
bool isEndOfWord;
TrieNode* children[26];
TrieNode() {
isEndOfWord = false;
// Initialize children
}
};Option A uses correct syntax and valid indices 0 to 25. Option A misses parentheses. Option A accesses index 26 (invalid). Option A skips index 0.
struct TrieNode {
bool isEndOfWord;
TrieNode* children[26];
TrieNode() {
isEndOfWord = false;
for (int i = 0; i < 26; i++) children[i] = nullptr;
}
};
// Insert words: "cat", "car", "dog""cat" and "car" share 'c' and 'a' nodes, so those nodes are shared. The nodes are:
Root (1)
c (2)
a (3)
t (4) for "cat"
r (5) for "car"
d (6) for "dog"
o (7) for "dog"
g (8) for "dog"
Total nodes = 8.