Skip to content

Commit 0aafd4b

Browse files
committed
Implement ternary search keys and keysWithPrefix
1 parent 223e74f commit 0aafd4b

File tree

2 files changed

+39
-4
lines changed

2 files changed

+39
-4
lines changed

Algorithms/DataStructures/SearchTries/TernarySearchTries.cs

+36-2
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
using System;
22
using System.Collections.Generic;
3+
using Algorithms.DataStructures.Queue;
34
using Algorithms.Utils;
45

56
namespace Algorithms.DataStructures.SearchTries
@@ -112,10 +113,43 @@ public bool ContainsKey(string key)
112113
return false;
113114
}
114115

115-
public IEnumerable<string> Keys { get; }
116+
public IEnumerable<string> Keys
117+
{
118+
get
119+
{
120+
var queue = new QueueLinkedList<string>();
121+
122+
Collect(root, "", queue);
123+
124+
return queue;
125+
}
126+
}
127+
128+
private void Collect(Node x, string prefix, IQueue<string> queue)
129+
{
130+
if (x == null)
131+
{
132+
return;
133+
}
134+
if (!ObjectUtil.IsNullOrDefault(x.value))
135+
{
136+
queue.Enqueue(prefix);
137+
}
138+
Collect(x.left, prefix, queue);
139+
Collect(x.mid, prefix + x.key, queue);
140+
Collect(x.right, prefix, queue);
141+
}
142+
116143
public IEnumerable<string> KeysWithPrefix(string prefix)
117144
{
118-
throw new System.NotImplementedException();
145+
IQueue<string> queue = new QueueLinkedList<string>();
146+
147+
Node x = Get(root, prefix, 0);
148+
if (x != null)
149+
{
150+
Collect(x, prefix, queue);
151+
}
152+
return queue;
119153
}
120154
}
121155
}

AlgorithmsUnitTest/DataStrutures/SearchTries/TernarySearchTriesUnitTest.cs

+3-2
Original file line numberDiff line numberDiff line change
@@ -34,13 +34,14 @@ public void TestSearchTries()
3434
Assert.False(map.ContainsKey("two"));
3535
Assert.False(map.IsEmpty);
3636

37-
/*
37+
3838

3939
foreach(var key in map.Keys)
4040
{
4141
console.WriteLine("{0}", key);
4242
}
4343

44+
4445
map["test"] = 3;
4546
map["te"] = 4;
4647
map["team"] = 4;
@@ -52,7 +53,7 @@ public void TestSearchTries()
5253
count++;
5354
console.WriteLine("{0}", key);
5455
}
55-
Assert.Equal(3, count);*/
56+
Assert.Equal(3, count);
5657
}
5758
}
5859
}

0 commit comments

Comments
 (0)