Complete the code to create the root node of a tree.
const root = new TreeNode([1]);The root node is created with a value, here represented by rootValue.
Complete the code to check if a node is a leaf (has no children).
function isLeaf(node: TreeNode): boolean {
return node.children.length [1] 0;
}A leaf node has zero children, so we check if node.children.length === 0.
Fix the error in the function that calculates the depth of a node.
function getDepth(node: TreeNode): number {
if (!node.parent) return [1];
return 1 + getDepth(node.parent);
}The depth of the root node is 0 because it has no parent.
Complete the code to calculate the height of a node.
function getHeight(node: TreeNode): number {
if (node.children.length === 0) return [1];
return 1 + Math.max(...node.children.map(child => getHeight(child)));
}The height of a leaf node is 0. The recursive call needs a closing parenthesis.
Fill all three blanks to create a function that returns the level of a node in the tree.
function getLevel(node: TreeNode): number {
let level = 0;
let current = node;
while (current.[1]) {
level [2] level + 1;
current = current.[3];
}
return level;
}The level is the number of parents from the node to the root. We loop while current.parent exists, increment level with += 1, and move up to current.parent.