Bird
Raised Fist0
DSA Javascriptprogramming~10 mins

Top View of Binary Tree in DSA Javascript - Execution Trace

Choose your learning style10 modes available
Concept Flow - Top View of Binary Tree
Start at root node
↓
Assign horizontal distance = 0
↓
Use queue for level order traversal
↓
For each node dequeued:
↓
Check if horizontal distance seen before?
↓
Add node to top view
↓
Ignore node for top view
↓
Enqueue left child with hd-1
↓
Enqueue right child with hd+1
↓
Repeat until queue empty
↓
Sort nodes by horizontal distance
↓
Print top view nodes
Traverse the tree level by level, track horizontal distances, and record the first node at each horizontal distance to get the top view.
Execution Sample
DSA Javascript
function topView(root) {
  let queue = [{node: root, hd: 0}];
  let topViewMap = new Map();
  while(queue.length) {
    let {node, hd} = queue.shift();
    if (!topViewMap.has(hd)) topViewMap.set(hd, node.val);
    if (node.left) queue.push({node: node.left, hd: hd - 1});
    if (node.right) queue.push({node: node.right, hd: hd + 1});
  }
  return [...topViewMap.entries()].sort((a,b) => a[0]-b[0]).map(x => x[1]);
}
This code finds the top view of a binary tree by level order traversal and tracking horizontal distances.
Execution Table
StepOperationNode Visited (val)Horizontal Distance (hd)Top View Map (hd: val)Queue StateVisual State
1Start with root10{}[{node:1, hd:0}]1(0)
2Dequeue node10{0:1}[{node:2, hd:-1}, {node:3, hd:1}]1(0)
3Dequeue node2-1{0:1, -1:2}[{node:3, hd:1}, {node:4, hd:-2}, {node:5, hd:0}]2(-1) -> 1(0)
4Dequeue node31{0:1, -1:2, 1:3}[{node:4, hd:-2}, {node:5, hd:0}, {node:6, hd:0}, {node:7, hd:2}]2(-1) -> 1(0) -> 3(1)
5Dequeue node4-2{0:1, -1:2, 1:3, -2:4}[{node:5, hd:0}, {node:6, hd:0}, {node:7, hd:2}]4(-2) -> 2(-1) -> 1(0) -> 3(1)
6Dequeue node50{0:1, -1:2, 1:3, -2:4}[{node:6, hd:0}, {node:7, hd:2}]4(-2) -> 2(-1) -> 1(0) -> 3(1)
7Dequeue node60{0:1, -1:2, 1:3, -2:4}[{node:7, hd:2}]4(-2) -> 2(-1) -> 1(0) -> 3(1)
8Dequeue node72{0:1, -1:2, 1:3, -2:4, 2:7}[]4(-2) -> 2(-1) -> 1(0) -> 3(1) -> 7(2)
9Queue empty--{-2:4, -1:2, 0:1, 1:3, 2:7}[]Top view nodes collected
💡 Queue is empty, all nodes processed, top view map complete
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 4After Step 5After Step 6After Step 7After Step 8Final
queue[{1,0}][{2,-1},{3,1}][{3,1},{4,-2},{5,0}][{4,-2},{5,0},{6,0},{7,2}][{5,0},{6,0},{7,2}][{6,0},{7,2}][{7,2}][][]
topViewMap{}{0:1}{0:1,-1:2}{0:1,-1:2,1:3}{0:1,-1:2,1:3,-2:4}{0:1,-1:2,1:3,-2:4}{0:1,-1:2,1:3,-2:4}{0:1,-1:2,1:3,-2:4,2:7}{-2:4,-1:2,0:1,1:3,2:7}
Key Moments - 3 Insights
Why do we only add a node to the top view map if its horizontal distance is not already present?
Because the top view shows the first node visible at each horizontal distance from the top. Later nodes at the same horizontal distance are hidden behind the first one. See execution_table steps 2, 3, and 6 where nodes with hd=0 are ignored after the first.
Why do we use a queue and level order traversal instead of depth-first traversal?
Level order ensures we visit nodes top-down, so the first node at each horizontal distance is the topmost. Depth-first might visit lower nodes first, causing incorrect top view. See execution_table steps showing queue states.
How do horizontal distances change when moving left or right?
Moving left decreases horizontal distance by 1, moving right increases it by 1. This helps track node positions horizontally. See execution_table steps 3 and 4 where left child hd is hd-1 and right child hd is hd+1.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at Step 5, what nodes are currently in the topViewMap?
A{0:1, -1:2, 1:3, -2:4}
B{0:1, -1:2, 1:3}
C{-1:2, 1:3, -2:4}
D{}
💡 Hint
Check the 'Top View Map' column at Step 5 in execution_table
At which step does the horizontal distance 2 first get added to the topViewMap?
AStep 6
BStep 7
CStep 8
DStep 9
💡 Hint
Look for when hd=2 appears in the 'Top View Map' column in execution_table
If the root node had no left child, how would the queue state change after Step 2?
AQueue would have only right child with hd=1
BQueue would be empty
CQueue would have left child with hd=-1
DQueue would have both children with hd=0
💡 Hint
Refer to queue state changes in variable_tracker and execution_table Step 2
Concept Snapshot
Top View of Binary Tree:
- Use level order traversal with a queue
- Track horizontal distance (hd) for each node
- Record first node at each hd in a map
- Left child hd = parent hd - 1
- Right child hd = parent hd + 1
- Sort map by hd keys to print top view
Full Transcript
To find the top view of a binary tree, we start at the root with horizontal distance zero. We use a queue to do a level order traversal. For each node, if its horizontal distance is not recorded yet, we add it to the top view map. We enqueue left and right children with hd-1 and hd+1 respectively. This way, the first node encountered at each horizontal distance is recorded. After processing all nodes, we sort the map by horizontal distance and print the node values. This method ensures we see the nodes visible from the top, ignoring nodes hidden behind others at the same horizontal distance.

Practice

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

Solution

  1. Step 1: Understand the top view concept

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

    Left or right views show nodes from sides, and leaf nodes are only the bottom nodes.
  3. Final Answer:

    Nodes visible when the tree is viewed from above -> Option D
  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 JavaScript data structure is best suited to store nodes by their horizontal distance when computing the top view of a binary tree?
easy
A. Set
B. Array
C. Map
D. Stack

Solution

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

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

    A Map allows storing key-value pairs with efficient lookup and insertion.
  3. Final Answer:

    Map -> Option C
  4. Quick Check:

    Map stores horizontal distance keys [OK]
Hint: Use Map for key-value horizontal distance storage [OK]
Common Mistakes:
  • Using Array which is index-based, not key-based
  • Using Set which stores only unique values without keys
  • Using Stack which is LIFO, not suitable here
3. What is the output of the following code snippet that prints the top view of the binary tree?
class Node {
  constructor(data) {
    this.data = data;
    this.left = null;
    this.right = null;
  }
}

function topView(root) {
  if (!root) return [];
  const map = new Map();
  const queue = [{ node: root, hd: 0 }];
  while (queue.length) {
    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 });
  }
  return [...map.entries()]
    .sort((a, b) => a[0] - b[0])
    .map(entry => entry[1]);
}

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));
medium
A. [2, 1, 3, 5]
B. [2, 1, 3]
C. [2, 1, 4, 3, 5]
D. [1, 2, 3, 4, 5]

Solution

  1. Step 1: Traverse the tree with horizontal distances

    Start at root (1) with hd=0, add left child (2) hd=-1, right child (3) hd=1, then 4 at hd=0 (ignored since hd=0 exists), 5 at hd=2.
  2. Step 2: Collect first nodes at each horizontal distance

    Map stores hd:-1=2, hd:0=1, hd:1=3, hd:2=5. Sorted by hd: -1,0,1,2 gives [2,1,3,5].
  3. Final Answer:

    [2, 1, 3, 5] -> Option A
  4. Quick Check:

    Top view nodes by hd = [2,1,3,5] [OK]
Hint: First node at each horizontal distance is in top view [OK]
Common Mistakes:
  • Including nodes hidden behind others at same hd
  • Not sorting by horizontal distance before output
  • Adding nodes multiple times for same hd
4. Identify the bug in this top view function and select the correct fix:
function topView(root) {
  if (!root) return [];
  const map = new Map();
  const queue = [{ node: root, hd: 0 }];
  while (queue.length) {
    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 [...map.entries()]
    .sort((a, b) => a[0] - b[0])
    .map(entry => entry[1]);
}
medium
A. Replace queue.pop() with queue.shift() to process nodes in correct order
B. Change map to a Set to avoid duplicate nodes
C. Remove sorting before returning the result
D. Add a visited set to avoid infinite loops

Solution

  1. Step 1: Understand queue usage in BFS

    Using queue.pop() removes last element, making it a stack (DFS), not BFS. BFS requires queue.shift() to process nodes in FIFO order.
  2. Step 2: Fix the traversal order

    Replacing pop() with shift() ensures nodes are processed level by level, correctly capturing top view nodes.
  3. Final Answer:

    Replace queue.pop() with queue.shift() to process nodes in correct order -> Option A
  4. Quick Check:

    BFS needs shift(), not pop() [OK]
Hint: Use shift() for BFS queue, pop() is for stack [OK]
Common Mistakes:
  • Using pop() causing wrong traversal order
  • Using Set instead of Map losing key-value pairs
  • Skipping sorting which orders output incorrectly
5. Given a binary tree where multiple nodes share the same horizontal distance and level, how should the top view algorithm decide which node to include in the output?
hard
A. Include the node that appears last in level order traversal at that horizontal distance
B. Include the node that appears first in level order traversal at that horizontal distance
C. Include the node with the maximum value at that horizontal distance
D. Include all nodes at that horizontal distance

Solution

  1. Step 1: Understand node conflicts at same horizontal distance and level

    When nodes share horizontal distance and level, top view includes the first encountered node in level order (BFS) traversal.
  2. Step 2: Reason why first node is chosen

    Because BFS visits nodes level by level from left to right, the first node at that horizontal distance is visible from top.
  3. Final Answer:

    Include the node that appears first in level order traversal at that horizontal distance -> Option B
  4. Quick Check:

    Top view = first node at hd in BFS order [OK]
Hint: Pick first node at horizontal distance in BFS [OK]
Common Mistakes:
  • Choosing node by max value instead of order
  • Including all nodes causing duplicates
  • Choosing last node instead of first
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