0
0
DSA Typescriptprogramming~10 mins

Why Trees Exist and What Linked Lists and Arrays Cannot Do in DSA Typescript - Test Your Knowledge

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete 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'
A[]
B{}
Cnull
D0
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.
2fill in blank
medium

Complete 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'
Ashift
Bpush
Cpop
Dunshift
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.
3fill in blank
hard

Fix 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'
A==
B!=
C>
D<
Attempts:
3 left
💡 Hint
Common Mistakes
Using == 0 which checks for no children.
Using != 0 which is less clear than > 0.
4fill in blank
hard

Fill 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'
Anode
Bcount
Cchildren
Dchild
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.
5fill in blank
hard

Fill 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'
Aval
Bchildren
Dvalue
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.