Trie

Trie Node & Dictionary Search Tree

Refere to https://leetcode.com/problems/implement-trie-prefix-tree/

Let's consider a problem that we want to search an word from a dictionary.
For example,

dictionary = {apple, ball, boat, code, command, coworker, zebra}
words = command

M : the length of the word we want to search
N : number of words in the dictionary

  • Brute-Force
    Firstly, we come up with an idea that store the dictionary into a hash set. Then, compare each "command" to all the words in the dictionary.
    The time complexity here will become M x N.
  • Well arrange BST
    To reduce the complexity, we can use binary search if we sort the dictionary in ascending order.

    Here, the time complexity become M x log(N).
  • Trie Node
    Using Trie, we can search the key in O(M) time. However the penalty is on Trie storage requirements.
class TrieNode{ public: bool isword; vector<TrieNode*> child; TrieNode() : isword(false){ for(int i = 0; i < 26; ++i) { child.push_back(NULL); } }; }; class Trie { TrieNode* root; public: /** Initialize your data structure here. */ Trie() { root = new TrieNode(); } /** Inserts a word into the trie. */ void insert(string word) { TrieNode* curr = root; for(auto c : word) { int tmp = c - 'a'; // this child node has not been construct if(!curr->child[tmp]) { curr->child[tmp] = new TrieNode(); } curr = curr->child[tmp]; } curr->isword = true; } /** Returns if the word is in the trie. */ bool search(string word) { TrieNode* curr = root; for(auto c : word) { int tmp = c - 'a'; if(!curr -> child[tmp]) return false; curr = curr -> child[tmp]; } return curr->isword; } /** Returns if there is any word in the trie that starts with the given prefix. */ bool startsWith(string prefix) { TrieNode* curr = root; for(auto c : prefix) { int tmp = c - 'a'; if(!curr -> child[tmp]) return false; curr = curr -> child[tmp]; } return true; } };