Left Side View of Binary Tree in DSA Javascript - Time & Space Complexity
We want to understand how the time needed to find the left side view of a binary tree changes as the tree grows.
How does the number of nodes affect the work done to get the left side view?
Analyze the time complexity of the following code snippet.
function leftSideView(root) {
if (!root) return [];
const result = [];
const queue = [root];
while (queue.length > 0) {
const levelSize = queue.length;
for (let i = 0; i < levelSize; i++) {
const node = queue.shift();
if (i === 0) result.push(node.val);
if (node.left) queue.push(node.left);
if (node.right) queue.push(node.right);
}
}
return result;
}
This code finds the left side view by visiting nodes level by level and picking the first node at each level.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The while loop runs once per level, and the inner for loop visits every node in the tree exactly once.
- How many times: Each node is processed once, so total operations grow with the number of nodes n.
As the tree grows, the number of nodes increases, and the code visits each node once.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 visits |
| 100 | About 100 visits |
| 1000 | About 1000 visits |
Pattern observation: The work grows directly with the number of nodes, so doubling nodes roughly doubles the work.
Time Complexity: O(n)
This means the time to find the left side view grows linearly with the number of nodes in the tree.
[X] Wrong: "Since we only pick one node per level, the time is O(height) or O(log n)."
[OK] Correct: Even though we pick one node per level for the result, we still visit every node to know which is first at each level, so the time depends on all nodes, not just levels.
Understanding this helps you explain how tree traversal works and how to analyze algorithms that visit all nodes once, a key skill in many coding challenges.
"What if we used recursion instead of a queue for level order traversal? How would the time complexity change?"