Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to create a new node with given value.
DSA Javascript
class Node { constructor(data) { this.data = data; this.left = null; this.right = null; } } const root = new Node([1]);
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using null or undefined as node data
Using a string instead of a number
✗ Incorrect
The root node should be created with the value 10 as data.
2fill in blank
mediumComplete the code to add a left child node to the root.
DSA Javascript
root.left = new Node([1]); Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Assigning null or undefined instead of a node
Using a string instead of a number
✗ Incorrect
The left child node should have the value 5.
3fill in blank
hardFix the error in the function to calculate the top view horizontal distance.
DSA Javascript
function topView(root) {
const map = new Map();
const queue = [];
queue.push({ node: root, hd: [1] });
// hd means horizontal distance
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Starting horizontal distance at 1 or -1
Using null instead of a number
✗ Incorrect
The horizontal distance of the root node is 0 by definition.
4fill in blank
hardFill both blanks to correctly update the horizontal distance for left and right children.
DSA Javascript
while (queue.length > 0) { const { node, hd } = queue.shift(); if (!map.has(hd)) { map.set(hd, node.data); } if (node.left) queue.push({ node: node.left, hd: hd [1] 1 }); if (node.right) queue.push({ node: node.right, hd: hd [2] 1 }); }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using addition for left child
Using multiplication or division instead of addition/subtraction
✗ Incorrect
Left child horizontal distance is parent's hd minus 1, right child is parent's hd plus 1.
5fill in blank
hardFill all three blanks to create the final top view array from the map.
DSA Javascript
const sortedKeys = Array.from(map.keys()).sort((a, b) => a [1] b); const topViewArr = sortedKeys.map(key => map.get(key)); return topViewArr; // returns array of node.data in top view order
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using '>' which sorts in descending order
Using '+' which is arithmetic, not comparison
✗ Incorrect
Sorting keys in ascending order requires comparing with '-' to order properly.