3. What will be the output of the following C++ code snippet that inserts words into a Trie and searches for prefix "app"?
class TrieNode {
public:
TrieNode* children[26];
bool isEnd;
TrieNode() {
for(int i=0; i<26; i++) children[i] = nullptr;
isEnd = false;
}
};
class Trie {
public:
TrieNode* root;
Trie() { root = new TrieNode(); }
void insert(string word) {
TrieNode* node = root;
for(char c : word) {
int idx = c - 'a';
if(!node->children[idx])
node->children[idx] = new TrieNode();
node = node->children[idx];
}
node->isEnd = true;
}
bool startsWith(string prefix) {
TrieNode* node = root;
for(char c : prefix) {
int idx = c - 'a';
if(!node->children[idx]) return false;
node = node->children[idx];
}
return true;
}
};
int main() {
Trie trie;
trie.insert("apple");
trie.insert("app");
cout << (trie.startsWith("app") ? "Yes" : "No") << endl;
cout << (trie.startsWith("apl") ? "Yes" : "No") << endl;
return 0;
}