using System; using System.Collections.Generic; class TrieNode { public Dictionary<char, TrieNode> Children = new Dictionary<char, TrieNode>(); public bool IsWordEnd = false; } class Trie { private TrieNode root = new TrieNode(); public void Insert(string word) { var node = root; foreach (var ch in word) { if (!node.Children.ContainsKey(ch)) { node.Children[ch] = new TrieNode(); } node = node.Children[ch]; } node.IsWordEnd = true; } public List<string> StartsWith(string prefix) { var node = root; foreach (var ch in prefix) { if (!node.Children.ContainsKey(ch)) return new List<string>(); node = node.Children[ch]; } var results = new List<string>(); DFS(node, prefix, results); return results; } private void DFS(TrieNode node, string path, List<string> results) { if (node.IsWordEnd) results.Add(path); foreach (var kvp in node.Children) { DFS(kvp.Value, path + kvp.Key, results); } } } class Program { static void Main() { var trie = new Trie(); trie.Insert("apple"); trie.Insert("app"); trie.Insert("application"); trie.Insert("apt"); var result = trie.StartsWith("app"); Console.WriteLine(string.Join(",", result)); } }
The code inserts four words: "apple", "app", "application", and "apt". The prefix searched is "app". The words starting with "app" are "app", "apple", and "application". The word "apt" starts with "ap" but not "app".
Words inserted: "cat", "car", "cart", "dog".
Shared prefix "ca" nodes are shared among "cat", "car", and "cart".
Nodes: root, 'c', 'a', 't' (for cat), 'r', 't' (for cart), 'd', 'o', 'g'. Detailed count including root: 9 nodes total.
public bool SearchPrefix(string prefix) { var node = root; foreach (var ch in prefix) { node = node.Children[ch]; } return true; }
The code accesses node.Children[ch] without checking if the key exists. If the prefix character is missing, this causes a KeyNotFoundException.
All inserted words start with "ba" so all are returned.
Searching prefix requires traversing k characters to reach the node, then DFS to collect m matched words. So complexity is O(k + m).
