0
0
DSA Javascriptprogramming~10 mins

Why Trees Exist and What Linked Lists and Arrays Cannot Do in DSA Javascript - 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 root node for a tree.

DSA Javascript
const root = { value: 10, children: [1] };
Drag options to blanks, or click blank then click option'
Anull
B{}
C[]
D0
Attempts:
3 left
💡 Hint
Common Mistakes
Using {} which is an object, not a list.
Using null which means no children but we want an empty list.
Using 0 which is a number, not a list.
2fill in blank
medium

Complete the code to add a child node to the root's children array.

DSA Javascript
root.children.[1]({ value: 20, children: [] });
Drag options to blanks, or click blank then click option'
Apush
Bunshift
Cshift
Dpop
Attempts:
3 left
💡 Hint
Common Mistakes
Using pop which removes the last element.
Using shift which removes the first element.
Using unshift which adds to the start, not the end.
3fill in blank
hard

Fix the error in the function that counts total nodes in a tree.

DSA Javascript
function countNodes(node) {
  let count = 1;
  for (const child of node.children) {
    count += countNodes([1]);
  }
  return count;
}
Drag options to blanks, or click blank then click option'
Achild
Bnode
Cchildren
Dcount
Attempts:
3 left
💡 Hint
Common Mistakes
Passing node causes infinite recursion.
Passing children is undefined in this scope.
Passing count is a number, not a node.
4fill in blank
hard

Fill both blanks to create a function that finds a node by value in a tree.

DSA Javascript
function findNode(node, value) {
  if (node.value === [1]) return node;
  for (const child of node.[2]) {
    const found = findNode(child, value);
    if (found) return found;
  }
  return null;
}
Drag options to blanks, or click blank then click option'
Avalue
Bchildren
Cchild
Dval
Attempts:
3 left
💡 Hint
Common Mistakes
Comparing to val which is undefined.
Looping over child which is a variable, not a property.
Looping over node which is an object, not iterable.
5fill in blank
hard

Fill all three blanks to create a function that collects all values in a tree into an array.

DSA Javascript
function collectValues(node) {
  let values = [[1]];
  for (const child of node.[2]) {
    values = values.concat(collectValues([3]));
  }
  return values;
}
Drag options to blanks, or click blank then click option'
Anode.value
Bchildren
Cchild
Dnode
Attempts:
3 left
💡 Hint
Common Mistakes
Using node instead of child in recursion.
Using node.children inside the loop instead of child.
Starting values with an empty array instead of including current node's value.