Complete the code to create a new Trie node with an empty children object.
function createNode() {
return { children: [1] };
}The children of a Trie node should be an empty object to hold child nodes by character keys.
Complete the code to check if a character exists in the current Trie node's children.
if (node.children.hasOwnProperty([1])) { // character exists }
We check if the children object has the key named by the variable char.
Fix the error in the search function to return true if the word is found in the Trie.
function search(word) {
let node = root;
for (let char of word) {
if (!node.children.hasOwnProperty(char)) {
return false;
}
node = node.children[[1]];
}
return node.isEnd === true;
}We must use the current character variable 'char' to move to the next node.
Fill both blanks to insert a word into the Trie correctly.
function insert(word) {
let node = root;
for (let char of word) {
if (!node.children.hasOwnProperty([1])) {
node.children[[2]] = createNode();
}
node = node.children[char];
}
node.isEnd = true;
}We check and add the child node using the current character 'char' in both blanks.
Fill all three blanks to create a function that searches for a prefix in the Trie.
function startsWith(prefix) {
let node = root;
for (let [1] of prefix) {
if (!node.children.hasOwnProperty([2])) {
return false;
}
node = node.children[[3]];
}
return true;
}The loop variable is 'char', and we use 'char' to check and move through children.