Implement Trie (Prefix Tree) LeetCode solution in JavaScript

1
var Trie = function () {
2
this.children = {};
3
this.word = false;
4
};
5

6
/**
7
* @param {string} word
8
* @return {void}
9
*/
10
Trie.prototype.insert = function (word) {
11
if (!word) {
12
this.word = true;
13
return null;
14
}
15
let head = word[0];
16
let tail = word.substring(1);
17

18
if (!this.children[head]) {
19
this.children[head] = new Trie();
20
}
21
this.children[head].insert(tail);
22
};
23

24
/**
25
* @param {string} word
26
* @return {boolean}
27
*/
28
Trie.prototype._search = function (word, method) {
29
if (!word) {
30
if (method === "search") {
31
return this.word;
32
} else {
33
return true;
34
}
35
}
36
let head = word[0];
37
let tail = word.substring(1);
38

39
if (!this.children[head]) {
40
return false;
41
}
42

43
return this.children[head][method](tail);
44
};
45

46
/**
47
* @param {string} word
48
* @return {boolean}
49
*/
50
Trie.prototype.search = function (word) {
51
return this._search(word, "search");
52
};
53

54
/**
55
* @param {string} prefix
56
* @return {boolean}
57
*/
58
Trie.prototype.startsWith = function (prefix) {
59
return this._search(prefix, "startsWith");
60
};
61

62
/**
63
* Your Trie object will be instantiated and called as such:
64
* var obj = new Trie()
65
* obj.insert(word)
66
* var param_2 = obj.search(word)
67
* var param_3 = obj.startsWith(prefix)
68
*/

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0