0
0
DSA Javascriptprogramming~10 mins

Top View of Binary Tree in DSA Javascript - Interactive Practice

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

Complete 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'
Anull
B10
C'root'
Dundefined
Attempts:
3 left
💡 Hint
Common Mistakes
Using null or undefined as node data
Using a string instead of a number
2fill in blank
medium

Complete 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'
A5
Bnull
C'left'
Dundefined
Attempts:
3 left
💡 Hint
Common Mistakes
Assigning null or undefined instead of a node
Using a string instead of a number
3fill in blank
hard

Fix 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'
A1
B-1
C0
Dnull
Attempts:
3 left
💡 Hint
Common Mistakes
Starting horizontal distance at 1 or -1
Using null instead of a number
4fill in blank
hard

Fill 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'
A-
B+
C*
D/
Attempts:
3 left
💡 Hint
Common Mistakes
Using addition for left child
Using multiplication or division instead of addition/subtraction
5fill in blank
hard

Fill 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'
A-
B>
C<
D+
Attempts:
3 left
💡 Hint
Common Mistakes
Using '>' which sorts in descending order
Using '+' which is arithmetic, not comparison