# 208 Implement Trie (Prefix Tree)

Implement a trie with`insert`,`search`, and`startsWith`methods.

**Note:**\
You may assume that all inputs are consist of lowercase letters`a-z`.

Constructs of a Trie are described in my Datastructures and Algorithms A gitbook.

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


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://maksimdan.gitbook.io/interview-practice-problems/leetcode_sessions/208-implement-trie-prefix-tree.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
