Skip to content

Commit ce42aaa

Browse files
authored
[ PS ] : Implement Trie (Prefix Tree)
1 parent 8b957b5 commit ce42aaa

File tree

1 file changed

+65
-0
lines changed

1 file changed

+65
-0
lines changed
+65
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
const Node = function (value) {
2+
this.value = value;
3+
this.children = {};
4+
this.data = null;
5+
}
6+
7+
const Trie = function () {
8+
this.root = new Node(null);
9+
};
10+
11+
/**
12+
* @param {string} word
13+
* @return {void}
14+
*/
15+
Trie.prototype.insert = function (word) {
16+
let parent = this.root;
17+
18+
for (let i = 0; i < word.length; i++) {
19+
if (!parent.children[word[i]]) {
20+
parent.children[word[i]] = new Node(word[i]);
21+
}
22+
parent = parent.children[word[i]];
23+
}
24+
25+
parent.data = word;
26+
};
27+
28+
/**
29+
* @param {string} word
30+
* @return {boolean}
31+
*/
32+
Trie.prototype.search = function (word) {
33+
let parent = this.root;
34+
let i = 0;
35+
36+
while (i < word.length && parent.children[word[i]]) {
37+
parent = parent.children[word[i]];
38+
i += 1;
39+
}
40+
41+
return parent.data === word;
42+
};
43+
44+
/**
45+
* @param {string} prefix
46+
* @return {boolean}
47+
*/
48+
Trie.prototype.startsWith = function (prefix) {
49+
let parent = this.root;
50+
51+
for (let char of prefix) {
52+
if (!parent.children[char]) return false;
53+
parent = parent.children[char];
54+
}
55+
56+
return true;
57+
};
58+
59+
/**
60+
* Your Trie object will be instantiated and called as such:
61+
* var obj = new Trie()
62+
* obj.insert(word)
63+
* var param_2 = obj.search(word)
64+
* var param_3 = obj.startsWith(prefix)
65+
*/

0 commit comments

Comments
 (0)