0
0
DSA Typescriptprogramming~5 mins

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

Choose your learning style9 modes available
Time Complexity: Bottom View of Binary Tree
O(n log 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: TreeNode | null): number[] {
  if (!root) return [];
  const queue: Array<[TreeNode, number]> = [[root, 0]];
  const map = new Map<number, number>();

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

  return Array.from(map.entries())
    .sort((a, b) => a[0] - b[0])
    .map(entry => entry[1]);
}
    

This code finds the bottom view of a binary tree by level order traversal, tracking horizontal distances.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The while loop processes each node once.
  • How many times: Exactly once per node, so n times for n nodes.
  • Inside the loop, map updates and queue operations happen once per node.
  • Sorting the map entries happens once after traversal, with entries up to the number of unique horizontal distances.
How Execution Grows With Input

As the tree grows, the number of nodes n increases, so the loop runs n times.

Input Size (n)Approx. Operations
10About 10 loop passes + sorting ~10 entries
100About 100 loop passes + sorting ~100 entries
1000About 1000 loop passes + sorting ~1000 entries

Pattern observation: The operations grow roughly in direct proportion to n, with sorting adding a small extra cost.

Final Time Complexity

Time Complexity: O(n log n)

This means the time grows a bit faster than the number of nodes because of sorting the horizontal distances after traversal.

Common Mistake

[X] Wrong: "The time complexity is just O(n) because we visit each node once."

[OK] Correct: While visiting nodes is O(n), sorting the horizontal distances at the end takes extra time, making the total O(n log n).

Interview Connect

Understanding this time complexity helps you explain how traversal and sorting combine in tree problems, a common skill interviewers look for.

Self-Check

"What if we used a balanced tree or priority queue to keep horizontal distances sorted during traversal? How would the time complexity change?"