0
0
DSA Typescriptprogramming~5 mins

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

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

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

How does the number of nodes affect the work done to see the tree from the right side?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


function rightSideView(root: TreeNode | null): number[] {
  if (!root) return [];
  const queue: TreeNode[] = [root];
  const result: number[] = [];

  while (queue.length > 0) {
    const levelSize = queue.length;
    for (let i = 0; i < levelSize; i++) {
      const node = queue.shift()!;
      if (node.left) queue.push(node.left);
      if (node.right) queue.push(node.right);
      if (i === levelSize - 1) result.push(node.val);
    }
  }
  return result;
}
    

This code visits each node level by level and records the last node's value at each level to get the right side view.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The while loop runs once per tree level, and the inner for loop visits every node in that level.
  • How many times: Each node is visited exactly once during the entire traversal.
How Execution Grows With Input

As the number of nodes increases, 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 grow linearly with the number of nodes.

Final Time Complexity

Time Complexity: O(n)

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

Common Mistake

[X] Wrong: "The time depends on the height of the tree only because we process level by level."

[OK] Correct: Even though we process level by level, every node is visited once, so the total time depends on the total number of nodes, not just the height.

Interview Connect

Understanding this helps you explain how breadth-first search works and how to analyze tree traversals, a common skill in coding interviews.

Self-Check

What if we used a depth-first search instead of breadth-first search? How would the time complexity change?