---
# System prepended metadata

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

---

# 1804. Implement Trie II (Prefix Tree)
###### tags: `Leetcode` `Medium` `Trie`
Link: https://leetcode.com/problems/implement-trie-ii-prefix-tree/
## Code
```java=
class Trie {
    class TrieNode{
        TrieNode[] children = new TrieNode[26];
        int prefixCount = 0;
        int wordCount = 0;
    }
    
    TrieNode root;
    
    public Trie() {
        root = new TrieNode();   
    }
    
    public void insert(String word) {
        TrieNode curr = root;
        for(int i = 0;i < word.length();i++){
            if(curr.children[word.charAt(i)-'a']==null){
                curr.children[word.charAt(i)-'a'] = new TrieNode();
            }
            curr.children[word.charAt(i)-'a'].prefixCount++;
            curr = curr.children[word.charAt(i)-'a'];
        }
        curr.wordCount++;
    }
    
    public int countWordsEqualTo(String word) {
        TrieNode curr = root;
        for(int i = 0;i < word.length();i++){
            if(curr.children[word.charAt(i)-'a']==null){
                return 0;
            }
            curr = curr.children[word.charAt(i)-'a'];
        }
        return curr.wordCount;
    }
    
    public int countWordsStartingWith(String prefix) {
        TrieNode curr = root;
        for(int i = 0;i < prefix.length();i++){
            if(curr.children[prefix.charAt(i)-'a']==null){
                return 0;
            }
            curr = curr.children[prefix.charAt(i)-'a'];
        }
        return curr.prefixCount;
    }
    
    public void erase(String word) {
        TrieNode curr = root;
        for(int i = 0;i < word.length();i++){
            curr.children[word.charAt(i)-'a'].prefixCount--;
            curr = curr.children[word.charAt(i)-'a'];
        }
        curr.wordCount--;
    }
}
```