0
0
DSA Javascriptprogramming~5 mins

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

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

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

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

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


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

This code finds the bottom view of a binary tree by traversing nodes level by level and tracking horizontal distances.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The while loop that processes each node once.
  • How many times: Exactly once per 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 and updates
100About 100 visits and updates
1000About 1000 visits and updates

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 bottom view grows in direct proportion to the number of nodes in the tree.

Common Mistake

[X] Wrong: "The time complexity is more than linear because we update the map multiple times for the same horizontal distance."

[OK] Correct: Each node is processed once, and map updates happen once per node, so total work is still proportional to the number of nodes.

Interview Connect

Understanding this linear time complexity helps you explain how tree traversals work efficiently and shows you can analyze algorithms that use queues and maps together.

Self-Check

"What if we used a recursive depth-first traversal instead of a queue? How would the time complexity change?"