# 208. Implement Trie (Prefix Tree)

![](https://4272748102-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-LekNH5IywF8mjBxFcnu%2Fuploads%2FcuRrTXVvhYXAy5nEcB3w%2F%E5%9C%96%E7%89%87.png?alt=media\&token=3f5ccd88-f178-4ca3-bd5f-e2388e32b550)

![](https://4272748102-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-LekNH5IywF8mjBxFcnu%2Fuploads%2FWQM5enS8cX2lIHjQpOhg%2F%E5%9C%96%E7%89%87.png?alt=media\&token=09d64b07-ef8e-4b69-9e11-b116eecefb68)

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