Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to create a simple tree node with a value.
DSA Typescript
class TreeNode { value: number; children: TreeNode[]; constructor(value: number) { this.value = value; this.children = [1]; } }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using {} instead of [] for children.
Setting children to null or 0.
✗ 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.
DSA Typescript
function addChild(parent: TreeNode, child: TreeNode): void {
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.
Using shift or unshift which affect the start of the array.
✗ Incorrect
push adds the child node to the end of the children array.
3fill in blank
hardFix the error in the linked list node definition to correctly link nodes.
DSA Typescript
class ListNode { value: number; next: [1] | null; constructor(value: number) { this.value = value; this.next = null; } }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using primitive types like number or string for next.
Forgetting to allow null for the last node.
✗ Incorrect
The next property should be of type ListNode to link to the next node.
4fill in blank
hardFill both blanks to create a function that converts an array to a linked list.
DSA Typescript
function arrayToLinkedList(arr: number[]): ListNode | null {
if (arr.length === 0) return null;
const head = new ListNode(arr[0]);
let current = head;
for (let i = 1; i [1] arr.length; i++) {
current.next = new ListNode(arr[[2]]);
current = current.next;
}
return head;
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using <= causes out-of-bounds error.
Using 0 instead of i for array index.
✗ Incorrect
The loop runs while i < arr.length and uses arr[i] to create new nodes.
5fill in blank
hardFill both blanks to create a function that prints tree values in preorder.
DSA Typescript
function preorder(node: TreeNode | null): void {
if (node === null) return;
console.log(node.[1]);
for (const child of node.[2]) {
preorder(child);
}
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Missing parentheses in recursive call.
Using wrong property names.
✗ Incorrect
Print node.value, loop over node.children, and call preorder(child) with parentheses.