HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Is this a reasonable Trie implementation?

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
thisimplementationreasonabletrie

Problem

http://en.wikipedia.org/wiki/Trie

The basic idea is to support fast searches via prefix matching. In my implementation, I allow each node to store all of the words that match its given prefix, and then if the word length exceeds the length of the node's prefix, it passes the word into its children for further storage.

```
public class TrieNode
{
private string Prefix { get; set; }
private IList Items { get; set; }
private IDictionary ChildNodes { get; set; }
private IEqualityComparer Comparer { get; set; }

public TrieNode() : this(StringComparer.CurrentCulture) { }
public TrieNode(IEqualityComparer comparer) : this(comparer, string.Empty) { }

private TrieNode(IEqualityComparer comparer, string prefix)
{
if (prefix == null)
throw new ArgumentNullException("Invalid prefix");

this.Prefix = prefix;
this.Items = new List();
this.ChildNodes = new Dictionary(comparer);
this.Comparer = comparer;
}

public void Add(string word)
{
if (word == null)
throw new InvalidOperationException("Cannot add null to list");

if (word.Length this.Prefix.Length)
{
string childKey = word.Substring(0, this.Prefix.Length + 1);
if (!this.ChildNodes.ContainsKey(childKey))
{
this.ChildNodes.Add(childKey, new TrieNode(this.Comparer, childKey));
}

this.ChildNodes[childKey].Add(word);
}
}

public void AddRange(IEnumerable words)
{
foreach (string word in words)
this.Add(word);
}

public ReadOnlyCollection FindMatches(string searchPrefix)
{
if (searchPrefix == null)
throw new InvalidOperationException("Cannot search on null strings");

if (this.Comparer.Equals(searchPrefix, this.Prefix))
{
return new ReadOnlyCollection(this.Items);
}
else

Solution

Instead of returning a collection, why not return an IEnumerable? Then you would perform no list copying, and it would be low cost to return an Enumerable that actually recurses through all the children lists.

Context

StackExchange Code Review Q#2195, answer score: 6

Revisions (0)

No revisions yet.