private void DFS(Node current, StringBuilder sb) { foreach (char c in current.children.Keys) { if (this.suggestions.Count < 10) { sb.Append(c); if (current.ChildNode(c).isWord) { this.suggestions.Add(sb.ToString()); } DFS(current.ChildNode(c), sb); sb.Remove(sb.Length - 1, 1); } } }
private void Insert(Node current, char[] letters, int index) { if (index < letters.Length) { if ((current.children.Count == 0 || !current.children.ContainsKey(letters[index]))) { current.children[letters[index]] = new Node(letters[index]); } current = current.children[letters[index]]; Insert(current, letters, index + 1); } else { current.isWord = true; } }
private void Search(Node current, char[] prefix, int index, StringBuilder sb) { if (index < prefix.Length && current.children.ContainsKey(prefix[index])) { sb.Append(prefix[index]); current = current.ChildNode(prefix[index]); Search(current, prefix, index + 1, sb); } else { if (current.isWord) { this.suggestions.Add(sb.ToString()); } DFS(current, sb); } }
public Trie() { root = new Node('$'); }