Understanding the Problem
The Left View of a Binary Tree refers to the set of nodes visible when the tree is viewed from the left side. At each level of the tree, the leftmost node is considered part of the left view.
To extract this view, we need to explore the tree level by level (using Breadth First Search). At each level, the first node we encounter from left to right is the one visible from the left side.
Step-by-Step Solution with Example
step 1: Visualize the tree
Let's take a sample binary tree:
1
/ 2 3
/ 4 5 6
When viewed from the left side, we see: 1 → 2 → 4
step 2: Use Level Order Traversal
We perform a BFS traversal using a queue. At each level, we process all nodes, and the first node we encounter is added to the left view list.
step 3: Initialize the queue
Start with the root node in the queue. We'll also track the level size to identify the first node at each level.
step 4: Traverse each level
For each level:
- Record the first node we dequeue (this is the leftmost for the level).
- Enqueue its left and right children, if they exist.
step 5: Build the result
Collect the first node from each level and add it to the result list representing the left view.
step 6: Output the final view
For the example above, the result would be: [1, 2, 4]
Edge Cases
Case 1: Left-Skewed Tree
If the tree only has left children like [10, 20, 30], all nodes are visible from the left. Output: [10, 20, 30]
Case 2: Right-Skewed Tree
Even when all nodes are on the right side like [7, null, 8, null, 9], each level still has only one node, so all nodes are visible. Output: [7, 8, 9]
Case 3: Tree with Missing Left Children
In some levels, the left child might be missing but the right child exists. The algorithm should still pick the first node seen at that level, regardless of being a left or right child.
Case 4: Empty Tree
If the tree is empty (null root), the output should be an empty list: []
Finally
To summarize, solving the Left View of a Binary Tree involves understanding that we need the first node seen at every level during a BFS traversal. By using a queue and processing level by level, we can handle any shape of tree—including skewed, sparse, or empty trees. This approach is efficient and beginner-friendly.