# Trie

as known as prefix tree.

### Implementation

```cpp
struct TrieNode {
    TrieNode *next[26] = {};
    int count = 0;
};

class Trie {
private:
    TrieNode root;
    TrieNode* searchToNode(string &prefix) {
        auto node = &root;
        for (char c : prefix) {
            if (!node->next[c - 'a']) return NULL;
            node = node->next[c - 'a'];
        }
        return node;
    }
public:
    void insert(string word) {
        auto node = &root;
        for (char c : word) {
            if (!node->next[c - 'a']) node->next[c - 'a'] = new TrieNode();
            node = node->next[c - 'a'];
        }
        node->count++;
    }

    bool search(string word) {
        auto node = searchToNode(word);
        return node && node->count;
    }

    bool startsWith(string prefix) {
        return searchToNode(prefix);
    }
};
```

## Problems

* [208. Implement Trie (Prefix Tree) (Medium)](https://leetcode.com/problems/implement-trie-prefix-tree/) **Direct Implementation**
* [212. Word Search II (Hard)](https://leetcode.com/problems/word-search-ii/)
* [745. Prefix and Suffix Search (Hard)](https://leetcode.com/problems/prefix-and-suffix-search/)
* [839. Similar String Groups (Hard)](https://leetcode.com/problems/similar-string-groups/)
* [1032. Stream of Characters (Hard)](https://leetcode.com/problems/stream-of-characters/)


---

# 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://liuzhenglaichn.gitbook.io/algorithm/data-structure/trie.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.
