Right Side View of Binary Tree in DSA Typescript - Time & Space 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?
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 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.
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 |
|---|---|
| 10 | About 10 visits |
| 100 | About 100 visits |
| 1000 | About 1000 visits |
Pattern observation: The operations grow linearly with the number of nodes.
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.
[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.
Understanding this helps you explain how breadth-first search works and how to analyze tree traversals, a common skill in coding interviews.
What if we used a depth-first search instead of breadth-first search? How would the time complexity change?