#include#include using namespace std; class TrieNode{ public: unordered_map children; bool isEnd; TrieNode() { isEnd = false; } }; class Trie{ public: TrieNode* root; Trie() { root = new TrieNode(); } void insert(string word) { TrieNode* currNode = root; for(char c : word) { if(currNode->children.find(c) == currNode->children.end()){ currNode->children[c] = new TrieNode(); } currNode = currNode->children[c]; } currNode->isEnd = true; } bool search(string word) { TrieNode* currNode = root; for(char c : word) { if(currNode->children.find(c) == currNode->children.end()) { return false; } currNode = currNode->children[c]; } return currNode->isEnd; } }; int main() { Trie dict; dict.insert("apple"); dict.insert("banana"); dict.insert("pear"); if(dict.search("pear")) { cout << "Found pear in the dictionary" << endl; } else { cout << "Could not find pear in the dictionary" << endl; } if(dict.search("orange")) { cout << "Found orange in the dictionary" << endl; } else { cout << "Could not find orange in the dictionary" << endl; } return 0; }
#includeDescription: The code creates a Trie data structure and inserts four words into it: "apple", "banana", "pear", "peach". It then searches for the autocomplete suggestions for the prefix "p". It prints the list of words that start with "p". Package Library: Standard Library#include #include using namespace std; class TrieNode{ public: unordered_map children; bool isEnd; TrieNode() { isEnd = false; } }; class Trie{ public: TrieNode* root; Trie() { root = new TrieNode(); } void insert(string word) { TrieNode* currNode = root; for(char c : word) { if(currNode->children.find(c) == currNode->children.end()){ currNode->children[c] = new TrieNode(); } currNode = currNode->children[c]; } currNode->isEnd = true; } void autocomplete(string prefix, vector & results) { TrieNode* currNode = root; for(char c : prefix) { if(currNode->children.find(c) == currNode->children.end()) { return; } currNode = currNode->children[c]; } dfs(currNode, prefix, results); } void dfs(TrieNode* currNode, string prefix, vector & results) { if(currNode->isEnd){ results.push_back(prefix); } for(auto it : currNode->children){ dfs(it.second, prefix+it.first, results); } } }; int main() { Trie dict; dict.insert("apple"); dict.insert("banana"); dict.insert("pear"); dict.insert("peach"); string prefix = "p"; vector results; dict.autocomplete(prefix, results); cout << "Autocomplete suggestions for prefix " << prefix << ":" << endl; for(string result : results) { cout << result << endl; } return 0; }