Bird
Raised Fist0
DSA Typescriptprogramming~20 mins

Top View of Binary Tree in DSA Typescript - Practice Problems & Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Top View Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of Top View for a Simple Binary Tree
What is the printed top view of the binary tree after running the given code?
DSA Typescript
class Node {
  constructor(public data: number, public left: Node | null = null, public right: Node | null = null) {}
}

function topView(root: Node | null): number[] {
  if (!root) return [];
  const map = new Map<number, number>();
  const queue: Array<{node: Node; hd: number}> = [{node: root, hd: 0}];
  let minHd = 0, maxHd = 0;

  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});
    if (node.right) queue.push({node: node.right, hd: hd + 1});
    minHd = Math.min(minHd, hd);
    maxHd = Math.max(maxHd, hd);
  }

  const result = [];
  for (let i = minHd; i <= maxHd; i++) {
    result.push(map.get(i)!);
  }
  return result;
}

// Tree structure:
//       1
//      / \
//     2   3
//      \   \
//       4   5
const root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.right = new Node(4);
root.right.right = new Node(5);

console.log(topView(root));
A[1, 2, 3, 4, 5]
B[2, 1, 3]
C[4, 2, 1, 3, 5]
D[2, 1, 3, 5]
Attempts:
2 left
💡 Hint
Think about horizontal distances from the root and which nodes appear first at each horizontal distance.
🧠 Conceptual
intermediate
1:30remaining
Understanding Horizontal Distance in Top View
In the top view of a binary tree, what does the 'horizontal distance' (hd) represent?
AThe relative horizontal position of a node from the root, where left child decreases hd by 1 and right child increases hd by 1.
BThe distance of a node from the root measured along the edges.
CThe depth of a node in the tree, counting edges from the root.
DThe vertical level of a node from the root, starting at 0 for the root.
Attempts:
2 left
💡 Hint
Think about how left and right children affect the horizontal position relative to the root.
🔧 Debug
advanced
2:00remaining
Identify the Bug in Top View Implementation
What error will this code produce when run, and why? function topView(root) { if (!root) return []; const map = new Map(); const queue = [{node: root, hd: 0}]; while (queue.length > 0) { const {node, hd} = queue.pop(); if (!map.has(hd)) { map.set(hd, node.data); } if (node.left) queue.push({node: node.left, hd: hd - 1}); if (node.right) queue.push({node: node.right, hd: hd + 1}); } return Array.from(map.values()); }
AReturns the correct top view array.
BThrows a TypeError because map is used incorrectly.
CReturns an empty array because queue.pop() removes from the end, causing incorrect traversal order.
DReturns a reversed top view array compared to expected output.
Attempts:
2 left
💡 Hint
Consider how queue.pop() affects the order of node processing compared to queue.shift().
🚀 Application
advanced
2:30remaining
Top View of a Complex Binary Tree
Given the binary tree below, what is the top view output? // Tree structure: // 10 // / \ // 5 15 // / \ \ // 3 7 18 // \ / // 4 16 Use the top view logic where the first node at each horizontal distance is included.
A[3, 5, 10, 15, 16, 18]
B[3, 5, 10, 15, 18]
C[4, 5, 10, 15, 18]
D[3, 4, 5, 10, 15, 18]
Attempts:
2 left
💡 Hint
Calculate horizontal distances for each node and pick the first node encountered at each hd in level order.
🧠 Conceptual
expert
1:30remaining
Why Use Breadth-First Search for Top View?
Why is breadth-first search (BFS) preferred over depth-first search (DFS) when computing the top view of a binary tree?
ABFS processes nodes level by level, ensuring the first node at each horizontal distance is recorded, while DFS may miss this order.
BDFS uses less memory, so it is not suitable for top view calculation.
CBFS visits nodes in random order, which helps find the top view faster.
DDFS cannot track horizontal distances, so it cannot be used for top view.
Attempts:
2 left
💡 Hint
Think about the order nodes are visited and how that affects which nodes appear in the top view.

Practice

(1/5)
1. What does the top view of a binary tree represent?
easy
A. Nodes visible when the tree is viewed from the right side
B. Nodes visible when the tree is viewed from the left side
C. Nodes visible when the tree is viewed from above
D. All leaf nodes of the tree

Solution

  1. Step 1: Understand the top view concept

    The top view of a binary tree shows nodes visible from the top, ignoring nodes hidden behind others vertically.
  2. Step 2: Compare with other views

    Left or right views show nodes from sides, and leaf nodes are only the bottom-most nodes, so they differ from top view.
  3. Final Answer:

    Nodes visible when the tree is viewed from above -> Option C
  4. Quick Check:

    Top view = nodes seen from above [OK]
Hint: Top view shows nodes visible from above only [OK]
Common Mistakes:
  • Confusing top view with left or right view
  • Thinking top view includes all leaf nodes
  • Assuming top view shows all nodes
2. Which TypeScript data structure is best suited to store nodes with their horizontal distances while computing the top view of a binary tree?
easy
A. Map (key-value pairs)
B. Array
C. Set
D. Stack

Solution

  1. Step 1: Identify the need for key-value storage

    We need to store nodes with their horizontal distances as keys and node values as values.
  2. Step 2: Choose the appropriate data structure

    A Map allows storing keys (horizontal distances) with corresponding node values efficiently.
  3. Final Answer:

    Map (key-value pairs) -> Option A
  4. Quick Check:

    Use Map for horizontal distance to node mapping [OK]
Hint: Use Map to link horizontal distance and node [OK]
Common Mistakes:
  • Using Array which is index-based, not key-based
  • Using Set which stores unique values without keys
  • Using Stack which is LIFO, not suitable here
3. Given the following TypeScript code snippet for top view, what will be the printed output?
class Node {
  constructor(public data: number, public left: Node | null = null, public right: Node | null = null) {}
}

const root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.right = new Node(4);
root.left.right.right = new Node(5);
root.left.right.right.right = new Node(6);

function topView(root: Node) {
  const map = new Map();
  const queue: Array<[Node, number]> = [[root, 0]];

  while (queue.length) {
    const [node, hd] = queue.shift()!;
    if (!map.has(hd)) {
      map.set(hd, node.data);
    }
    if (node.left) queue.push([node.left, hd - 1]);
    if (node.right) queue.push([node.right, hd + 1]);
  }

  const sortedKeys = Array.from(map.keys()).sort((a, b) => a - b);
  const result = sortedKeys.map(key => map.get(key));
  console.log(result);
}

topView(root);
medium
A. [1, 2, 3, 4, 5, 6]
B. [2, 4, 1, 3, 6]
C. [2, 1, 3]
D. [2, 1, 3, 6]

Solution

  1. Step 1: Assign horizontal distances and track first nodes

    Root(1) at hd=0, left(2) at hd=-1, right(3) at hd=1. Next nodes 4 at hd=0 (ignored, already 1), 5 at hd=1 (ignored, already 3), 6 at hd=2 (new).
  2. Step 2: Collect nodes in order of horizontal distance

    Sorted keys: -1, 0, 1, 2 with values 2, 1, 3, 6 respectively.
  3. Final Answer:

    [2, 1, 3, 6] -> Option D
  4. Quick Check:

    Top view nodes = [2, 1, 3, 6] [OK]
Hint: First node at each horizontal distance is in top view [OK]
Common Mistakes:
  • Including nodes hidden behind others at same horizontal distance
  • Not sorting horizontal distances before output
  • Adding all nodes instead of first at each horizontal distance
4. Identify the bug in the following TypeScript code for top view of a binary tree:
function topView(root: Node) {
  const map = new Map();
  const queue: Array<[Node, number]> = [[root, 0]];

  while (queue.length) {
    const [node, hd] = queue.pop()!;
    if (!map.has(hd)) {
      map.set(hd, node.data);
    }
    if (node.left) queue.push([node.left, hd - 1]);
    if (node.right) queue.push([node.right, hd + 1]);
  }

  const sortedKeys = Array.from(map.keys()).sort((a, b) => a - b);
  const result = sortedKeys.map(key => map.get(key));
  console.log(result);
}
medium
A. Using queue.pop() instead of queue.shift() causes wrong traversal order
B. Not checking if root is null before processing
C. Not sorting the keys before printing result
D. Using Map instead of Set for horizontal distances

Solution

  1. Step 1: Analyze queue operation impact

    Using pop() removes from end, making traversal depth-first instead of breadth-first, breaking horizontal distance order.
  2. Step 2: Correct traversal method

    Using shift() removes from front, ensuring level order traversal needed for correct top view.
  3. Final Answer:

    Using queue.pop() instead of queue.shift() causes wrong traversal order -> Option A
  4. Quick Check:

    Use shift() for BFS queue [OK]
Hint: Use shift() for BFS queue, not pop() [OK]
Common Mistakes:
  • Using pop() causing DFS instead of BFS
  • Ignoring null root check (less critical here)
  • Not sorting keys before output (code does sort)
5. You have a binary tree where multiple nodes share the same horizontal distance and level. How should you modify the top view algorithm to always show the node with the smallest value at each horizontal distance?
hard
A. Store all nodes at each horizontal distance and pick the last inserted node
B. Update the map only if the new node's value is smaller than the existing one at that horizontal distance
C. Ignore horizontal distance and print nodes in level order
D. Use a stack instead of a queue for traversal

Solution

  1. Step 1: Understand the problem with duplicates

    When nodes share horizontal distance and level, default top view picks first encountered node, not necessarily smallest value.
  2. Step 2: Modify map update condition

    Update the map only if the new node's value is smaller than the stored value for that horizontal distance to ensure smallest value is shown.
  3. Final Answer:

    Update the map only if the new node's value is smaller than the existing one at that horizontal distance -> Option B
  4. Quick Check:

    Keep smallest node value per horizontal distance [OK]
Hint: Update map only if new node value is smaller [OK]
Common Mistakes:
  • Ignoring value comparison, keeping first node only
  • Using stack breaks level order needed
  • Storing all nodes wastes memory and complicates logic
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard