Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to create a tree node with a value and empty children array.
DSA Typescript
class TreeNode { value: number; children: TreeNode[]; constructor(val: number) { this.value = val; this.children = [1]; } }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using {} which creates an object instead of an array.
Setting children to null or 0 which are not arrays.
✗ Incorrect
The children property should be an empty array to hold child nodes.
2fill in blank
mediumComplete the code to add a child node to a tree node's children array.
DSA Typescript
function addChild(parent: TreeNode, child: TreeNode) {
parent.children.[1](child);
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using pop() which removes the last element instead of adding.
Using shift() or unshift() which affect the start of the array.
✗ Incorrect
Use push() to add a new child node at the end of the children array.
3fill in blank
hardFix the error in the code to check if a node has children.
DSA Typescript
function hasChildren(node: TreeNode): boolean {
return node.children.length [1] 0;
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using == 0 which checks for no children.
Using != 0 which is less clear than > 0.
✗ Incorrect
We check if the children array length is greater than 0 to know if there are children.
4fill in blank
hardFill both blanks to create a function that counts total nodes in a tree recursively.
DSA Typescript
function countNodes(node: TreeNode): number {
let count = 1;
for (const child of node.children) {
count += countNodes([1]);
}
return count;
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'node' which causes infinite recursion on the same node.
Using 'children' which is an array, not a node.
✗ Incorrect
We recursively count nodes by calling countNodes on each child node.
5fill in blank
hardFill all three blanks to create a function that finds a node by value in a tree.
DSA Typescript
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;
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'value' instead of 'val' in comparisons.
Looping over 'value' instead of 'children'.
Passing wrong variable in recursive call.
✗ Incorrect
We compare node.value to val, loop over children, and pass val recursively.