---
# System prepended metadata

title: 0208. Implement Trie (Prefix Tree)
tags: [Leetcode, Trie, Medium]

---

# 0208. Implement Trie (Prefix Tree)
###### tags: `Leetcode` `Medium` `Trie`
Link: https://leetcode.com/problems/implement-trie-prefix-tree/
## Code
```java=
class Trie {
    class TrieNode{
        TrieNode[] children = new TrieNode[26];
        boolean isWord = false;
    }
    TrieNode root;
    
    public Trie() {
        root = new TrieNode();    
    }
    
    public void insert(String word) {
        TrieNode curr = root;
        for(char c:word.toCharArray()){
            if(curr.children[c-'a']==null) curr.children[c-'a'] = new TrieNode();
            curr = curr.children[c-'a'];
        }
        curr.isWord = true;
    }
    
    public boolean search(String word) {
        TrieNode curr = root;
        for(char c:word.toCharArray()){
            if(curr.children[c-'a']==null) return false;
            curr = curr.children[c-'a'];
        }
        return curr.isWord;
    }
    
    public boolean startsWith(String prefix) {
        TrieNode curr = root;
        for(char c:prefix.toCharArray()){
            if(curr.children[c-'a']==null) return false;
            curr = curr.children[c-'a'];
        }
        return true;
    }
}
```