Summary
var displayTree = tree => console.log(JSON.stringify(tree, null, 2));
class Node{
constructor() {
this.keys = new Map();
this.end = false;
}
setEnd() {
this.end = true;
};
isEnd() {
return this.end;
}
}
class Trie{
constructor() {
this.root = new Node();
}
add(input,node=this.root){
if(!input)
{
node.setEnd();
return ;
} else{
if(!node.keys.has(input[0])){
node.keys.set(input[0],new Node());
}
return this.add(input.substr(1),node.keys.get(input[0]));
}
}
print(node=this.root, string='',words=[]) {
if (node.keys.size != 0) {
for (let letter of node.keys.keys()) {
this.print(node.keys.get(letter), string.concat(letter),words);
};
if(node.isEnd()) words.push(string)
} else {
words.push(string);
}
return words;
}
// Only change code below this line
isWord(word){
let node = this.root;
while (word.length > 0) {
if (!node.keys.has(word[0])) {
return false;
} else {
node = node.keys.get(word[0]);
word = word.substr(1);
};
};
return node.isEnd() ? true : false;
}
// Only change code above this line
};
let myTrie = new Trie()
myTrie.add('ball');
myTrie.add('bat');
myTrie.add('doll');
myTrie.add('dork');
myTrie.add('do');
myTrie.add('dorm')
myTrie.add('send')
myTrie.add('sense')
console.log(myTrie.isWord('doll'))
console.log(myTrie.isWord('dor'))
console.log(myTrie.isWord('dorf'))
console.log(myTrie.print())