# Trie

## 经典题目

[*208 Implement Trie* (*Prefix Tree*) ](https://leetcode.com/problems/implement-trie-prefix-tree/description/)

Trie：字典树。

* Search：O（N）（N：word的长度）
* Insert：O（N）（N：word的长度）

```java
class Trie {
    class TrieNode {
        private TrieNode[] children;
        private boolean isEnd;
        public TrieNode() {
            this.children = new TrieNode[26];
        }
        public void put(char ch, TrieNode node) {
            children[ch - 'a'] = node;
        }
        public TrieNode get(char ch) {
            return children[ch - 'a'];
        }
        public void setEnd() {
            this.isEnd = true;
        }
        public boolean isEnd() {
            return isEnd;
        }
    }
    
    TrieNode root;
    /** Initialize your data structure here. */
    public Trie() {
        root = new TrieNode();
    }
    
    /** Inserts a word into the trie. */
    public void insert(String word) {
        TrieNode node = root;
        for(int i = 0; i < word.length(); i++) {
            char cur = word.charAt(i);
            if (node.get(cur) == null) {
                node.put(cur, new TrieNode());
            }
            node = node.get(cur);
        }
        node.isEnd = true;
    }
    
    /** Return the last TrieNode if the word is in the trie, otherwise return null */
    private TrieNode find(String word) {
        TrieNode node = root;
        for (int i = 0; i < word.length(); i++) {
            char cur = word.charAt(i);
            if (node.get(cur) == null) {
                return null;
            }
            node = node.get(cur);
        }
        return node;
    }
    
    /** Returns if the word is in the trie. */
    public boolean search(String word) {
        TrieNode node = find(word);
        return node != null && node.isEnd();
    }
    
    /** Returns if there is any word in the trie that starts with the given prefix. */
    public boolean startsWith(String prefix) {
        TrieNode node = find(prefix);
        return node != null;
    }
}
```


---

# 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://mabuxi.gitbook.io/mabuxi/leetcode-summary/data-structure/trie-1.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.
