- Notifications
You must be signed in to change notification settings - Fork 1.4k
/
Copy pathTrieNode.cs
121 lines (102 loc) · 3.21 KB
/
TrieNode.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
usingSystem;
usingSystem.Collections.Generic;
namespaceDataStructures.Trees
{
/// <summary>
/// The Trie Node.
/// </summary>
publicclassTrieNode
{
/// <summary>
/// Instance variables.
/// </summary>
publicvirtualcharKey{get;set;}
publicvirtualboolIsTerminal{get;set;}
publicvirtualTrieNodeParent{get;set;}
publicvirtualDictionary<char,TrieNode>Children{get;set;}
/// <summary>
/// CONSTRUCTORS
/// </summary>
publicTrieNode(charkey):this(key,false){}
publicTrieNode(charkey,boolisTerminal)
{
Key=key;
IsTerminal=isTerminal;
Children=newDictionary<char,TrieNode>();
}
/// <summary>
/// Return the word at this node if the node is terminal; otherwise, return null
/// </summary>
publicvirtualstringWord
{
get
{
if(!IsTerminal)
returnnull;
varcurr=this;
varstack=newStack<char>();
while(curr.Parent!=null)
{
stack.Push(curr.Key);
curr=curr.Parent;
}
returnnewString(stack.ToArray());
}
}
/// <summary>
/// Returns an enumerable list of key-value pairs of all the words that start
/// with the prefix that maps from the root node until this node.
/// </summary>
publicvirtualIEnumerable<String>GetByPrefix()
{
if(IsTerminal)
yieldreturnWord;
foreach(varchildKeyValinChildren)
foreach(varterminalNodeinchildKeyVal.Value.GetByPrefix())
yieldreturnterminalNode;
}
/// <summary>
/// Returns an enumerable collection of terminal child nodes.
/// </summary>
publicvirtualIEnumerable<TrieNode>GetTerminalChildren()
{
foreach(varchildinChildren.Values){
if(child.IsTerminal)
yieldreturnchild;
foreach(vargrandChildinchild.GetTerminalChildren())
if(grandChild.IsTerminal)
yieldreturngrandChild;
}
}
/// <summary>
/// Remove this element upto its parent.
/// </summary>
publicvirtualvoidRemove()
{
IsTerminal=false;
if(Children.Count==0&&Parent!=null)
{
Parent.Children.Remove(Key);
if(!Parent.IsTerminal)
Parent.Remove();
}
}
/// <summary>
/// IComparer interface implementation
/// </summary>
publicintCompareTo(TrieNodeother)
{
if(other==null)
return-1;
returnthis.Key.CompareTo(other.Key);
}
/// <summary>
/// Clears this node instance
/// </summary>
publicvoidClear()
{
Children.Clear();
Children=null;
}
}
}