-
Notifications
You must be signed in to change notification settings - Fork 0
/
trieSearch.js
41 lines (34 loc) · 843 Bytes
/
trieSearch.js
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
class trienode{
constructor(){
this.children={}
this.endOfWord=false
}
}
class trie{
constructor(){
this.root=new trienode()
}
insert(word){
let node=this.root
for(let i=0;i<word.length;i++){
let char=word[i]
if(!node.children[char]){
node.children[char]=new trienode
}
node=node.children[char]
}node.endOfWord=true
console.log(`"${word}" inserted`);
}
search(word){
let node=this.root
for(let i=0;i<word.length;i++){
let char=word[i]
if(!node.children[char]){
return false
}node=node.children[char]
} return node.endOfWord
}
}
let tr=new trie
tr.insert("apple")
console.log(tr.search("apple"));