Problem Statement
Given the root of a binary tree, return the nodes visible when the tree is viewed from the left side.
Only the first node at each level is visible.
Brute Force Intuition
In an interview, you can explain it like this:
Perform a level-order traversal (BFS). For every level, simply record the first node encountered.
Since BFS already processes nodes level by level, identifying the first node is straightforward.
Complexity
- Time Complexity: O(N)
- Space Complexity: O(N)
Moving Towards the Optimal Approach
Notice that during BFS:
Each Level
↓
Processed Together
If we know:
Level Size
then the very first node processed at that level is exactly the left view.
Pattern Recognition
Whenever you see:
- Left View
- Right View
- Level Wise Processing
Think:
Level Order Traversal (BFS)
Key Observation
For every level:
First Node
↓
Left View
Continue BFS until all levels are processed.
Optimal Approach
Step 1
Push the root into a queue.
Step 2
Process one level at a time.
For every level:
size = queue.size();
Step 3
The first node:
i == 0
belongs to the left view.
Step 4
Push:
Left Child
↓
Right Child
into the queue.
Optimal Java Solution
class Solution {
ArrayList<Integer> leftView(Node root) {
ArrayList<Integer> ans = new ArrayList<>();
if (root == null)
return ans;
Queue<Node> q = new LinkedList<>();
q.offer(root);
while (!q.isEmpty()) {
int size = q.size();
for (int i = 0; i < size; i++) {
Node curr = q.poll();
if (i == 0)
ans.add(curr.data);
if (curr.left != null)
q.offer(curr.left);
if (curr.right != null)
q.offer(curr.right);
}
}
return ans;
}
}
Dry Run
1
/ \
2 3
/ \ \
4 5 6
Level 1
1
First Node:
1
Level 2
2 3
First Node:
2
Level 3
4 5 6
First Node:
4
Final Answer:
[1,2,4]
Why BFS Works?
BFS processes the tree level by level.
Since nodes are visited from left to right,
the first node encountered at every level is exactly the node visible from the left side.
Complexity Analysis
| Metric | Complexity |
|---|---|
| Time Complexity | O(N) |
| Space Complexity | O(N) |
Interview One-Liner
Perform a level-order traversal and record the first node encountered at every level.
Pattern Learned
Level Order
↓
First Node
↓
Left View
Similar Problems
- Left View of Binary Tree
- Right View of Binary Tree
- Top View
- Bottom View
- Zigzag Level Order Traversal
Memory Trick
Think:
One Level
↓
First Node
↓
Answer
Mental Model
Queue
↓
Process One Level
↓
Pick First Node
↓
Continue
Whenever you hear:
"Left View of Binary Tree"
your brain should immediately think:
Level Order Traversal + First Node of Every Level
Top comments (0)