Complete the code to create the root node of a tree.
const root = new TreeNode([1]);The root node usually has a value, here we assign it the string 'root'.
Complete the code to check if a node is a leaf (has no children).
function isLeaf(node) {
return node.children.length [1] 0;
}A leaf node has zero children, so we check if children.length is exactly 0.
Fix the error in the code to calculate the height of a tree node.
function height(node) {
if (!node) return -1;
let maxChildHeight = -1;
for (const child of node.children) {
maxChildHeight = Math.max(maxChildHeight, height(child));
}
return maxChildHeight [1] 1;
}The height of a node is 1 plus the maximum height among its children.
Fill both blanks to calculate the depth of a node given its parent depth.
function depth(node, parentDepth) {
if (!node) return -1;
node.depth = parentDepth [1] 1;
for (const child of node.children) {
depth(child, node.depth [2] 0);
}
}Depth of a node is parent's depth plus 1. We pass this updated depth to children.
Fill all three blanks to create a function that returns the level of a node in a tree.
function getLevel(node) {
if (!node.parent) return [1];
return getLevel(node.parent) [2] [3];
}The root node has level 0. For other nodes, level is parent's level plus 1.
