Complete the code to create a new Trie node with an empty children object.
class TrieNode { constructor() { this.children = [1]; this.isEndOfWord = false; } }
The children of a Trie node should be an empty object to hold child 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.hasOwnProperty([1])) {
node.children[char] = new TrieNode();
}
node = node.children[char];
}
node.isEndOfWord = true;
}We check if the current character 'char' exists as a key in the children object.
Fix the error in the search method to correctly check if a word exists in the Trie.
search(word) {
let node = this.root;
for (let char of word) {
if (!node.children[[1]]) {
return false;
}
node = node.children[char];
}
return node.isEndOfWord;
}We must check if the current character 'char' exists in the children object.
Fill both blanks to complete the DFS helper function that collects all words starting from a node.
dfs(node, prefix, results) {
if (node.isEndOfWord) {
results.push([1]);
}
for (let char in node.children) {
this.dfs(node.children[char], prefix [2] char, results);
}
}Push the current prefix as a word when isEndOfWord is true, and concatenate prefix and char with '+' when recursing.
Fill the blanks to complete the autocomplete method that returns all words starting with a prefix.
autocomplete(prefix) {
let node = this.root;
for (let char of prefix) {
if (!node.children[[1]]) {
return [];
}
node = node.children[char];
}
let results = [];
this.dfs(node, [2], results);
return results;
}Check if the current character 'char' exists in children, then call dfs with the full prefix string to collect words.