# 208. Implement Trie (Prefix Tree)

![](/files/J2IpKPi93kYE09zx8zRI)

![](/files/1SYdEGZX4WDCgrHbC5ST)

time: O(n), n is word len

space: O(26\*n), each node have 26 chars, in worst case, tire will have n level , n is word len

```java
class Trie {
    
    class TrieNode {
        Map<Character, TrieNode> sons;
        boolean isWord;
        String word;
        TrieNode() {
            this.sons = new HashMap<>();
            this.isWord = false;
            this.word = null;
        }
    }

    /** Initialize your data structure here. */
    private TrieNode root;
    public Trie() {
        root = new TrieNode();
    }
    
    /** Inserts a word into the trie. */
    public void insert(String word) {
        TrieNode node = root;
        for (char c : word.toCharArray()) {
            node.sons.computeIfAbsent(c, k -> new TrieNode());
            node = node.sons.get(c);
        }
        node.isWord = true;
        node.word = word;
    }
    
    private TrieNode getNode(String word) {
        TrieNode node = root;
        for (char c : word.toCharArray()) {
            TrieNode next = node.sons.get(c);
            if (next == null) {
                return null;
            }
            node = next;
        }
        return node;
    }
    
    /** Returns if the word is in the trie. */
    public boolean search(String word) {
        TrieNode node = getNode(word);
        return node != null && node.isWord;
    }
    
    
    /** Returns if there is any word in the trie that starts with the given prefix. */
    // ex: build: apple
    // input prefix: app (prefix 比較短
    // so getNode will return a node is going to app's last p, so next not null!
    public boolean startsWith(String prefix) { 
        TrieNode node = getNode(prefix);
        return node != null;
    }
}

/**
 * Your Trie object will be instantiated and called as such:
 * Trie obj = new Trie();
 * obj.insert(word);
 * boolean param_2 = obj.search(word);
 * boolean 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://timmybeeflin.gitbook.io/cracking-leetcode/trie/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.
