Complete the code to create a root node for a tree.
const root = { value: 10, children: [1] };The children of a tree node are stored in an array to hold multiple child nodes.
Complete the code to add a child node to the root's children array.
root.children.[1]({ value: 20, children: [] });
pop which removes the last element.shift which removes the first element.unshift which adds to the start, not the end.Use push to add a new child node at the end of the children array.
Fix the error in the function that counts total nodes in a tree.
function countNodes(node) {
let count = 1;
for (const child of node.children) {
count += countNodes([1]);
}
return count;
}node causes infinite recursion.children is undefined in this scope.count is a number, not a node.We must recursively count nodes starting from each child node, so pass child to the recursive call.
Fill both blanks to create a function that finds a node by value in a tree.
function findNode(node, value) {
if (node.value === [1]) return node;
for (const child of node.[2]) {
const found = findNode(child, value);
if (found) return found;
}
return null;
}val which is undefined.child which is a variable, not a property.node which is an object, not iterable.Compare node.value to the value parameter and loop over children array.
Fill all three blanks to create a function that collects all values in a tree into an array.
function collectValues(node) {
let values = [[1]];
for (const child of node.[2]) {
values = values.concat(collectValues([3]));
}
return values;
}node instead of child in recursion.node.children inside the loop instead of child.Start with the current node's value, loop over children, and recursively collect values from each child.