Implement a trie withinsert,search, andstartsWithmethods.
Note:
You may assume that all inputs are consist of lowercase lettersa-z.
Constructs of a Trie are described in my Datastructures and Algorithms A gitbook.
structTrieNode {TrieNode() {} unordered_map<char, TrieNode*> children;bool EOW =false;};classTrie {public: /** Initialize your data structure here. */Trie() { root =newTrieNode(); } /** Inserts a word into the trie. */voidinsert(string word) { TrieNode *iter = root;for (char c : word) {if (iter->children.find(c) ==iter->children.end()) { TrieNode *new_child =newTrieNode();iter->children.insert({c, new_child}); } iter =iter->children[c]; }iter->EOW =true; } /** Returns if the word is in the trie. */boolsearch(string word) { TrieNode *iter = root;for (char c : word) {if (iter->children.find(c) ==iter->children.end()) returnfalse;else iter =iter->children[c]; }returniter->EOW; } /** Returns if there is any word in the trie that starts with the given prefix. */boolstartsWith(string prefix) { TrieNode *iter = root;for (char c : prefix) {if (iter->children.find(c) ==iter->children.end()) returnfalse;else iter =iter->children[c]; }returntrue; }private: TrieNode *root;};/** * Your Trie object will be instantiated and called as such: * Trie obj = new Trie(); * obj.insert(word); * bool param_2 = obj.search(word); * bool param_3 = obj.startsWith(prefix); */