Skip to content

Commit 2d16acd

Browse files
committed
refactor: 208. Implement Trie (Prefix Tree)
1 parent e4aaeab commit 2d16acd

File tree

1 file changed

+24
-15
lines changed

1 file changed

+24
-15
lines changed

implement-trie-prefix-tree/gwbaik9717.js

Lines changed: 24 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,23 @@ var Trie = function () {
77
this.head = new Node();
88
};
99

10+
/**
11+
* @param {string} str
12+
* @return {TrieNode | null}
13+
*/
14+
Trie.prototype._traverse = function (str) {
15+
let current = this.head;
16+
17+
for (const chr of str) {
18+
if (!current.children.has(chr)) {
19+
return null;
20+
}
21+
current = current.children.get(chr);
22+
}
23+
24+
return current;
25+
};
26+
1027
/**
1128
* @param {string} word
1229
* @return {void}
@@ -30,32 +47,24 @@ Trie.prototype.insert = function (word) {
3047
* @return {boolean}
3148
*/
3249
Trie.prototype.search = function (word) {
33-
let current = this.head;
34-
35-
for (const chr of word) {
36-
if (!current.children.has(chr)) {
37-
return false;
38-
}
50+
const node = this._traverse(word);
3951

40-
current = current.children.get(chr);
52+
if (!node) {
53+
return false;
4154
}
4255

43-
return current.isEnd;
56+
return node.isEnd;
4457
};
4558

4659
/**
4760
* @param {string} prefix
4861
* @return {boolean}
4962
*/
5063
Trie.prototype.startsWith = function (prefix) {
51-
let current = this.head;
64+
const node = this._traverse(prefix);
5265

53-
for (const chr of prefix) {
54-
if (!current.children.has(chr)) {
55-
return false;
56-
}
57-
58-
current = current.children.get(chr);
66+
if (!node) {
67+
return false;
5968
}
6069

6170
return true;

0 commit comments

Comments
 (0)