Complete the code to create a new Trie node with an empty children object.
class TrieNode { constructor() { this.children = [1]; this.isEndOfWord = false; } }
We use an empty object {} to store children nodes by character keys.
Complete the code to insert a character into the Trie children if it does not exist.
insert(word) {
let node = this.root;
for (let char of word) {
if (!node.children[char]) {
node.children[char] = new TrieNode();
}
node = node.children[[1]];
}
node.isEndOfWord = true;
}We move to the child node corresponding to the current character char.
Fix the error in the search method to correctly check if a prefix exists in the Trie.
search(prefix) {
let node = this.root;
for (let char of prefix) {
if (!node.children[[1]]) {
return false;
}
node = node.children[char];
}
return true;
}We check if the current character char exists in the children of the current node.
Fill both blanks to complete the method that returns all words starting with a given prefix.
startsWith(prefix) {
let node = this.root;
for (let char of prefix) {
if (!node.children[[1]]) {
return [];
}
node = node.children[[2]];
}
const results = [];
function dfs(currentNode, path) {
if (currentNode.isEndOfWord) {
results.push(path);
}
for (let key in currentNode.children) {
dfs(currentNode.children[key], path + key);
}
}
dfs(node, prefix);
return results;
}char.Both blanks use char to access the child node for each character in the prefix.
Fill both blanks to complete the method that collects words from a Trie node using DFS.
collectWords(node, path, words) {
if (node.isEndOfWord) {
words.push([1]);
}
for (let char in node.children) {
this.collectWords(node.children[char], [2], words);
}
}We add the current path to words when a word ends, and extend the path with char when going deeper.