Skip to content

Commit 12ecc5e

Browse files
feat: implement-trie-prefix-tree
1 parent c09dd4d commit 12ecc5e

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
function TrieNode() {
2+
this.children = {};
3+
this.isEnd = false;
4+
}
5+
6+
function Trie() {
7+
this.root = new TrieNode();
8+
}
9+
10+
Trie.prototype.insert = function (word) {
11+
let node = this.root;
12+
for (let char of word) {
13+
if (!node.children[char]) {
14+
node.children[char] = new TrieNode();
15+
}
16+
node = node.children[char];
17+
}
18+
node.isEnd = true;
19+
};
20+
21+
Trie.prototype.search = function (word) {
22+
let node = this._traverse(word);
23+
return node !== null && node.isEnd === true;
24+
};
25+
26+
Trie.prototype.startsWith = function (prefix) {
27+
return this._traverse(prefix) !== null;
28+
};
29+
30+
Trie.prototype._traverse = function (str) {
31+
let node = this.root;
32+
for (let char of str) {
33+
if (!node.children[char]) return null;
34+
node = node.children[char];
35+
}
36+
return node;
37+
};

0 commit comments

Comments
 (0)