What will be the output of the following code snippet?
#include <iostream>
#include <unordered_map>
struct TrieNode {
std::unordered_map<char, TrieNode*> children;
bool isEndOfWord;
};
void insert(TrieNode* root, std::string word) {
TrieNode* current = root;
for (char ch : word) {
if (current->children.find(ch) == current->children.end()) {
current->children[ch] = new TrieNode();
}
current = current->children[ch];
}
current->isEndOfWord = true;
}
bool hasChildren(TrieNode* root) {
return !root->children.empty();
}
bool deleteHelper(TrieNode* root, std::string word, int index) {
if (index == word.length()) {
if (!root->isEndOfWord)
return false;
root->isEndOfWord = false;
return !hasChildren(root);
}
char ch = word[index];
if (root->children.find(ch) == root->children.end())
return false;
TrieNode* childNode = root->children[ch];
bool shouldDeleteCurrentNode = deleteHelper(childNode, word, index + 1);
if (shouldDeleteCurrentNode) {
root->children.erase(ch);
delete childNode;
return !hasChildren(root);
}
return false;
}
bool deleteWord(TrieNode* root, std::string word) {
return deleteHelper(root, word, 0);
}
int main() {
TrieNode* root = new TrieNode();
insert(root, "hello");
insert(root, "world");
deleteWord(root, "hello");
std::cout << countWords(root) << std::endl;
delete root;
return 0;
}
Correct answer is option 'A'. Can you explain this answer?