Right Side View of Binary Tree in DSA Javascript - 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) {
if (!root) return [];
const queue = [root];
const result = [];
while (queue.length > 0) {
const size = queue.length;
for (let i = 0; i < size; i++) {
const node = queue.shift();
if (node.left) queue.push(node.left);
if (node.right) queue.push(node.right);
if (i === size - 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 level, and inside it, the for loop visits every node at that level.
- How many times: Every node in the tree is visited exactly once during the for loops combined.
As the number of nodes (n) grows, the code visits each node once, so the total operations grow roughly in direct proportion to n.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 visits |
| 100 | About 100 visits |
| 1000 | About 1000 visits |
Pattern observation: The work grows linearly with the number of nodes.
Time Complexity: O(n)
This means the time to find the right side view grows directly with the number of nodes in the tree.
[X] Wrong: "Since we only take one node per level, the time complexity is O(height) or O(log n)."
[OK] Correct: Even though we record one node per level, we still visit every node to know which one is last at each level, so the time depends on all nodes, not just the height.
Understanding this helps you explain how level-by-level tree traversal works and why visiting all nodes is necessary, a common pattern in tree problems.
"What if we used a depth-first search instead of breadth-first search? How would the time complexity change?"