Implement Trie

Question

Implement a trie with insert, search, and startsWith methods.

Note:

You may assume that all inputs are consist of lowercase letters a-z.

Analysis

https://leetcode.com/articles/implement-trie-prefix-tree/

Trie Node Definition

class TrieNode {

    // R links to node children
    private TrieNode[] links;

    private final int R = 26;

    private boolean isEnd;

    public TrieNode() {
        links = new TrieNode[R];
    }

    public boolean containsKey(char ch) {
        return links[ch -'a'] != null;
    }
    public TrieNode get(char ch) {
        return links[ch -'a'];
    }
    public void put(char ch, TrieNode node) {
        links[ch -'a'] = node;
    }
    public void setEnd() {
        isEnd = true;
    }
    public boolean isEnd() {
        return isEnd;
    }
}

Solution

Implementation 1 - using hashmap for characters

A trie node should contains the character, its children and the flag that marks if it is a leaf node. You can use this diagram to walk though the Java solution.

LeetCode official solution

Java Implementation 2 - Using array for characters

Each trie node can only contains 'a'-'z' characters. So we can use a small array to store the character.

Reference

Last updated

Was this helpful?