-
Notifications
You must be signed in to change notification settings - Fork 0
/
TrieNode.ts
80 lines (70 loc) · 1.56 KB
/
TrieNode.ts
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
class TrieNode {
parent: TrieNode;
char: string;
children: TrieChildren;
isEndOfWord: boolean;
constructor(char: string) {
this.char = char;
this.children = {};
this.isEndOfWord = false;
}
// AddChild to add char
addChild(char: string) {
this.children[char] = new TrieNode(char);
}
addParent(parent: TrieNode) {
this.parent = parent;
}
// GetChild Char
getChild(char: string) {
return this.children[char];
}
// hasChild
hasChild(char: string) {
return this.children[char] !== undefined;
}
// Is End Of Sequence
setIsEndOfWord() {
this.isEndOfWord = true;
}
getWord() {
let word:string = '';
let current:TrieNode = this;
while (current.parent) {
// ascend the tree appending each character to word
word = current.char + word;
// make current the current's parent to go up the tree
current = current.parent;
}
return word;
}
}
interface TrieChildren {
a?: TrieNode;
b?: TrieNode;
c?: TrieNode;
d?: TrieNode;
e?: TrieNode;
f?: TrieNode;
g?: TrieNode;
h?: TrieNode;
i?: TrieNode;
j?: TrieNode;
k?: TrieNode;
l?: TrieNode;
m?: TrieNode;
n?: TrieNode;
o?: TrieNode;
p?: TrieNode;
q?: TrieNode;
r?: TrieNode;
s?: TrieNode;
t?: TrieNode;
u?: TrieNode;
v?: TrieNode;
w?: TrieNode;
x?: TrieNode;
y?: TrieNode;
z?: TrieNode;
}
export default TrieNode;