0
0
DSA Javascriptprogramming~5 mins

Top View of Binary Tree in DSA Javascript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Top View of Binary Tree
O(n)
Understanding Time Complexity

We want to understand how the time needed to find the top view of a binary tree changes as the tree grows.

How does the number of nodes affect the work done to get the top view?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


function topView(root) {
  if (!root) return [];
  const queue = [{ node: root, hd: 0 }];
  const map = new Map();
  while (queue.length) {
    const { node, hd } = queue.shift();
    if (!map.has(hd)) map.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 Array.from(map.values());
}
    

This code finds the top view of a binary tree by visiting nodes level by level and tracking their horizontal distance.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The while loop that visits each node once.
  • How many times: Once for every node in the tree (n times).
How Execution Grows With Input

As the number of nodes grows, the code visits each node once, so the work grows directly with the number of nodes.

Input Size (n)Approx. Operations
10About 10 visits
100About 100 visits
1000About 1000 visits

Pattern observation: The operations increase linearly as the tree size increases.

Final Time Complexity

Time Complexity: O(n)

This means the time to find the top view grows in direct proportion to the number of nodes in the tree.

Common Mistake

[X] Wrong: "The code visits nodes multiple times, so time is more than linear."

[OK] Correct: Each node is visited exactly once in the queue, so the total work is proportional to the number of nodes.

Interview Connect

Understanding this linear time complexity helps you explain how tree traversal works efficiently in real problems.

Self-Check

"What if we used a recursive approach instead of a queue? How would the time complexity change?"