//Insert a word into the Trie. O(m) time/space complexity. m is word length public void Insert(String word) { TrieArrayNode node = root; for (int i = 0; i < word.Length; ++i) { if (!node.ContainsKey(word[i])) { node.Put(word[i], new TrieArrayNode()); } node = node.Get(word[i]); } node.SetEnd(); }
//search a prefix(or whole key) in trie and //returns the node where search ends //O(m) time complexity, O(1) space complexity private TrieArrayNode SearchPrefix(string prefix) { TrieArrayNode node = root; for (int i = 0; i < prefix.Length; ++i) { if (node.ContainsKey(prefix[i])) { node = node.Get(prefix[i]); } else { return(null); } } return(node); }