Complete the code to create a tree node with a value and empty children array.
class TreeNode { value: number; children: TreeNode[]; constructor(val: number) { this.value = val; this.children = [1]; } }
The children property should be an empty array to hold child nodes.
Complete the code to add a child node to a tree node's children array.
function addChild(parent: TreeNode, child: TreeNode) {
parent.children.[1](child);
}Use push() to add a new child node at the end of the children array.
Fix the error in the code to check if a node has children.
function hasChildren(node: TreeNode): boolean {
return node.children.length [1] 0;
}We check if the children array length is greater than 0 to know if there are children.
Fill both blanks to create a function that counts total nodes in a tree recursively.
function countNodes(node: TreeNode): number {
let count = 1;
for (const child of node.children) {
count += countNodes([1]);
}
return count;
}We recursively count nodes by calling countNodes on each child node.
Fill all three blanks to create a function that finds a node by value in a tree.
function findNode(node: TreeNode, val: number): TreeNode | null {
if (node.value === [1]) return node;
for (const child of node.[2]) {
const found = findNode(child, [3]);
if (found) return found;
}
return null;
}We compare node.value to val, loop over children, and pass val recursively.
