-
Notifications
You must be signed in to change notification settings - Fork 299
/
Copy pathTernarySearchTree.cs
383 lines (326 loc) · 10.9 KB
/
TernarySearchTree.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace Advanced.Algorithms.DataStructures;
/// <summary>
/// A ternary search tree implementation.
/// </summary>
public class TernarySearchTree<T> : IEnumerable<T[]> where T : IComparable
{
private TernarySearchTreeNode<T> root;
public TernarySearchTree()
{
Count = 0;
}
public int Count { get; private set; }
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public IEnumerator<T[]> GetEnumerator()
{
return new TernarySearchTreeEnumerator<T>(root);
}
/// <summary>
/// Time complexity: O(m) where m is the length of entry.
/// </summary>
public void Insert(T[] entry)
{
Insert(ref root, null, entry, 0);
Count++;
}
/// <summary>
/// Insert a new record to this ternary search tree after finding the end recursively.
/// </summary>
private void Insert(ref TernarySearchTreeNode<T> currentNode,
TernarySearchTreeNode<T> parent,
T[] entry, int currentIndex)
{
//create new node if empty
if (currentNode == null) currentNode = new TernarySearchTreeNode<T>(parent, entry[currentIndex]);
var compareResult = currentNode.Value.CompareTo(entry[currentIndex]);
//current is greater? move left, move right otherwise
//if current is equal then move center
if (compareResult > 0)
{
//move left
var left = currentNode.Left;
Insert(ref left, parent, entry, currentIndex);
currentNode.Left = left;
}
else if (compareResult < 0)
{
//move right
var right = currentNode.Right;
Insert(ref right, parent, entry, currentIndex);
currentNode.Right = right;
}
else
{
if (currentIndex != entry.Length - 1)
{
//if equal we just skip to next element
var middle = currentNode.Middle;
Insert(ref middle, currentNode, entry, currentIndex + 1);
currentNode.Middle = middle;
}
//end of word
else
{
if (currentNode.IsEnd) throw new Exception("Item exists.");
currentNode.IsEnd = true;
}
}
}
/// <summary>
/// Deletes a record from this ternary search tree.
/// Time complexity: O(m) where m is the length of entry.
/// </summary>
public void Delete(T[] entry)
{
Delete(root, entry, 0);
Count--;
}
/// <summary>
/// Deletes a record from this TernarySearchTree after finding it recursively.
/// </summary>
private void Delete(TernarySearchTreeNode<T> currentNode,
T[] entry, int currentIndex)
{
//empty node
if (currentNode == null) throw new Exception("Item not found.");
var compareResult = currentNode.Value.CompareTo(entry[currentIndex]);
TernarySearchTreeNode<T> child;
//current is greater? move left, move right otherwise
//if current is equal then move center
if (compareResult > 0)
{
//move left
child = currentNode.Left;
Delete(child, entry, currentIndex);
//delete if middle is not end
//and we if have'nt deleted the node yet
if (child.HasChildren == false
&& !child.IsEnd)
currentNode.Left = null;
}
else if (compareResult < 0)
{
//move right
child = currentNode.Right;
Delete(child, entry, currentIndex);
//delete if middle is not end
//and we if have'nt deleted the node yet
if (child.HasChildren == false
&& !child.IsEnd)
currentNode.Right = null;
}
else
{
if (currentIndex != entry.Length - 1)
{
//if equal we just skip to next element
child = currentNode.Middle;
Delete(child, entry, currentIndex + 1);
//delete if middle is not end
//and we if have'nt deleted the node yet
if (child.HasChildren == false
&& !child.IsEnd)
currentNode.Middle = null;
}
//end of word
else
{
if (!currentNode.IsEnd) throw new Exception("Item not found.");
//remove this end flag
currentNode.IsEnd = false;
}
}
}
/// <summary>
/// Returns a list of records matching this prefix.
/// Time complexity: O(rm) where r is the number of results and m is the average length of each entry.
/// </summary>
public List<T[]> StartsWith(T[] prefix)
{
return StartsWith(root, prefix, 0);
}
/// <summary>
/// Recursively visit until end of prefix and then gather all suffixes under it.
/// </summary>
private List<T[]> StartsWith(TernarySearchTreeNode<T> currentNode, T[] searchPrefix, int currentIndex)
{
while (true)
{
if (currentNode == null) return new List<T[]>();
var compareResult = currentNode.Value.CompareTo(searchPrefix[currentIndex]);
//current is greater? move left, move right otherwise
//if current is equal then move center
if (compareResult > 0)
{
//move left
currentNode = currentNode.Left;
continue;
}
if (compareResult < 0)
{
//move right
currentNode = currentNode.Right;
continue;
}
//end of search Prefix, so gather all words under it
if (currentIndex != searchPrefix.Length - 1)
{
currentNode = currentNode.Middle;
currentIndex = currentIndex + 1;
continue;
}
var result = new List<T[]>();
GatherStartsWith(result, searchPrefix.ToList(), currentNode.Middle);
return result;
}
}
/// <summary>
/// Gathers all suffixes under this node appending with the given prefix
/// </summary>
private void GatherStartsWith(List<T[]> result, List<T> prefix, TernarySearchTreeNode<T> node)
{
while (true)
{
if (node == null)
{
result.Add(prefix.ToArray());
return;
}
//end of word
if (node.IsEnd)
//append to end of prefix for new prefix
result.Add(prefix.Concat(new[] { node.Value }).ToArray());
if (node.Left != null) GatherStartsWith(result, prefix, node.Left);
if (node.Middle != null)
{
//append to end of prefix for new prefix
prefix.Add(node.Value);
GatherStartsWith(result, prefix, node.Middle);
prefix.RemoveAt(prefix.Count - 1);
}
if (node.Right != null)
{
node = node.Right;
continue;
}
break;
}
}
/// <summary>
/// Returns true if the entry exist.
/// Time complexity: O(e) where e is the length of the given entry.
/// </summary>
public bool Contains(T[] entry)
{
return Search(root, entry, 0, false);
}
/// <summary>
/// Returns true if the entry prefix exist.
/// Time complexity: O(e) where e is the length of the given entry.
/// </summary>
public bool ContainsPrefix(T[] entry)
{
return Search(root, entry, 0, true);
}
/// <summary>
/// Find if the record exist recursively.
/// </summary>
private bool Search(TernarySearchTreeNode<T> currentNode, T[] searchEntry, int currentIndex, bool isPrefixSearch)
{
while (true)
{
//create new node if empty
if (currentNode == null) return false;
//end of word, so return
if (currentIndex == searchEntry.Length - 1) return isPrefixSearch || currentNode.IsEnd;
var compareResult = currentNode.Value.CompareTo(searchEntry[currentIndex]);
//current is greater? move left, move right otherwise
//if current is equal then move center
if (compareResult > 0)
{
//move left
currentNode = currentNode.Left;
continue;
}
if (compareResult < 0)
{
//move right
currentNode = currentNode.Right;
continue;
}
//if equal we just skip to next element
currentNode = currentNode.Middle;
currentIndex = currentIndex + 1;
}
}
}
internal class TernarySearchTreeNode<T> where T : IComparable
{
internal TernarySearchTreeNode(TernarySearchTreeNode<T> parent, T value)
{
Parent = parent;
Value = value;
}
internal bool IsEnd { get; set; }
internal T Value { get; set; }
internal bool HasChildren => !(Left == null && Middle == null && Right == null);
internal TernarySearchTreeNode<T> Parent { get; set; }
internal TernarySearchTreeNode<T> Left { get; set; }
internal TernarySearchTreeNode<T> Middle { get; set; }
internal TernarySearchTreeNode<T> Right { get; set; }
}
internal class TernarySearchTreeEnumerator<T> : IEnumerator<T[]> where T : IComparable
{
private readonly TernarySearchTreeNode<T> root;
private Stack<TernarySearchTreeNode<T>> progress;
internal TernarySearchTreeEnumerator(TernarySearchTreeNode<T> root)
{
this.root = root;
}
public bool MoveNext()
{
if (root == null) return false;
if (progress == null) progress = new Stack<TernarySearchTreeNode<T>>(new[] { root });
while (progress.Count > 0)
{
var next = progress.Pop();
foreach (var child in new[] { next.Left, next.Middle, next.Right }.Where(x => x != null))
progress.Push(child);
if (next.IsEnd)
{
Current = GetValue(next);
return true;
}
}
return false;
}
public void Reset()
{
progress = null;
Current = null;
}
public T[] Current { get; private set; }
object IEnumerator.Current => Current;
public void Dispose()
{
progress = null;
}
private T[] GetValue(TernarySearchTreeNode<T> next)
{
var result = new Stack<T>();
result.Push(next.Value);
while (next.Parent != null && !next.Parent.Value.Equals(default(T)))
{
next = next.Parent;
result.Push(next.Value);
}
return result.ToArray();
}
}