208 Implement Trie (Prefix Tree)

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.

struct TrieNode {
    TrieNode() {}
    unordered_map<char, TrieNode*> children;
    bool EOW = false;
};

class Trie {
    public:
        /** Initialize your data structure here. */
        Trie() {  root = new TrieNode(); }

        /** Inserts a word into the trie. */
        void insert(string word) {
            TrieNode *iter = root;
            for (char c : word) {
                if (iter->children.find(c) == iter->children.end()) {
                    TrieNode *new_child = new TrieNode();
                    iter->children.insert({c, new_child});
                }
                iter = iter->children[c];
            }
            iter->EOW = true;
        }

        /** Returns if the word is in the trie. */
        bool search(string word) {
            TrieNode *iter = root;
            for (char c : word) {
                if (iter->children.find(c) == iter->children.end()) 
                    return false;
                else iter = iter->children[c];
            }
            return iter->EOW;
        }

        /** Returns if there is any word in the trie that starts with the given prefix. */
        bool startsWith(string prefix) {
            TrieNode *iter = root;
            for (char c : prefix) {
                if (iter->children.find(c) == iter->children.end()) 
                    return false;
                else iter = iter->children[c];
            }
            return true;
        }

    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);
 */

Last updated