Given the root of a binary tree, imagine standing on its left side. Return the values of the nodes you can see, ordered from top to bottom — that is, the leftmost node at each level.
The tree is given in level-order (breadth-first), using null for missing children.
Input: root = [1, 2, 3, 4, 5, null, null, null, 6] Output: [1, 2, 4, 6] From the left you see the leftmost node at each of the four levels.
Input: root = [1, null, 3] Output: [1, 3] The 3 is the leftmost (only) node on level 1, even though it's a right child.
Input: root = [] Output: [] An empty tree shows nothing.
- The number of nodes is in the range [0, 100] - 1 <= Node.val <= 10^5
Standing on the left, the node you see at each level is the leftmost one. So this is level-order traversal where you keep only the first node of each level. Equivalently, a depth-first walk that visits the left child first and records the first node it reaches at each new depth.
“Leftmost node, or only left children?”
The leftmost node at each level, which may be a right child if the left side is missing.
“Empty tree?”
Return an empty list.
The left-side view is the first node of each level, so I run level-order BFS and keep the first node of every level.
Or I DFS left-child-first and record the first node I reach at each new depth.
Worked example — tree [1, 2, 3, 4, 5, null, null, null, 6]
1
/ \
2 3
/ \
4 5
\
6
level 0: leftmost 1
level 1: leftmost 2
level 2: leftmost 4
level 3: leftmost 6
result: [1, 2, 4, 6]
It's level-order with everything but each level's first node discarded.
If a level's leftmost node has no left child, its leftmost may descend from a right child.
Recursing left before right reaches each depth's leftmost node first; record on first arrival at a depth.
| Left-first DFS | BFS first-of-level | |
|---|---|---|
| Idea | Record first node reached at each new depth | Keep the first node dequeued per level |
| Time | O(n) | O(n) |
| Space | O(height) | O(n) |
Both are O(n); BFS reads directly as 'first of each level'. Full code is in the Approaches selector below.
Key takeaway
The left-side view is the leftmost (first) node at each level. Take it from level-order BFS, or from a left-first DFS that records the first node at each new depth. O(n) time.
bfs level by level:
append the first node of each level to the result