Lefty Nodes

Lefty Nodes

Return the leftmost value on each level of the tree, top to bottom (the "left view" of the tree).

leftyNodes(root)

Input format: level-order with x for missing children. Output the values space-separated.

Examples

3 11 4 4 x x 2    // → 3 11 4
1 2 3 x 4         // → 1 2 4
(empty)           // → (empty)

Walkthrough

Thinking it through

"The leftmost value on each level" is a question about the tree's structure level by level, not about any single root-to-leaf path. Depth-first search dives deep into one branch before backing out, making "what's the first node reached at depth 3?" awkward — you'd need to track depth separately from the traversal. It's fighting the grain.

Why breadth-first search fits naturally

BFS processes the tree in exactly the order this cares about: every node at depth 0, then depth 1, then depth 2, using a queue. Since BFS naturally groups work into complete levels, "the first node processed in this level's group" is directly the leftmost node — no separate depth bookkeeping.

Building the approach

  1. Start a queue with the root (skip if the tree is empty).
  2. Before working through a level, note the current queue size — that's exactly how many nodes belong to this level.
  3. Go through those nodes in dequeue order. The first one dequeued this round is the leftmost — record it.
  4. For every node processed, enqueue its left child before its right, so the next level's queue stays ordered left-to-right too.
  5. Repeat until the queue is empty.

Why 'left child before right child' is essential

The trick — "first dequeued this round is leftmost" — depends entirely on left-to-right enqueue order at every level. Enqueue right-before-left even once, and the leftmost node of the next level could land anywhere in the queue.

Why this is efficient

Every node is enqueued and dequeued once at constant cost — O(n) time. The queue can hold as many nodes as the widest level, up to O(n) in the worst case (a wide, shallow tree).

main.py
Console
Press Run to execute your code, or Submit to test and complete this problem.