Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to create the root node of a tree.
DSA Javascript
const root = new TreeNode([1]); Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using null or 0 as the root value which may not represent the root meaningfully.
✗ Incorrect
The root node usually has a value, here we assign it the string 'root'.
2fill in blank
mediumComplete the code to check if a node is a leaf (has no children).
DSA Javascript
function isLeaf(node) {
return node.children.length [1] 0;
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using > or !== which would not correctly identify leaf nodes.
✗ Incorrect
A leaf node has zero children, so we check if children.length is exactly 0.
3fill in blank
hardFix the error in the code to calculate the height of a tree node.
DSA Javascript
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;
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using subtraction or multiplication which gives wrong height values.
✗ Incorrect
The height of a node is 1 plus the maximum height among its children.
4fill in blank
hardFill both blanks to calculate the depth of a node given its parent depth.
DSA Javascript
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);
}
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using subtraction or multiplication which gives incorrect depths.
✗ Incorrect
Depth of a node is parent's depth plus 1. We pass this updated depth to children.
5fill in blank
hardFill all three blanks to create a function that returns the level of a node in a tree.
DSA Javascript
function getLevel(node) {
if (!node.parent) return [1];
return getLevel(node.parent) [2] [3];
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 1 as root level or subtracting which gives wrong levels.
✗ Incorrect
The root node has level 0. For other nodes, level is parent's level plus 1.