Problem
You are given the root of an n-ary tree, where each node may have multiple children. Imagine yourself standing on the left side of the tree. Write a program to return a list of the values of the nodes visible from the left side, ordered from top to bottom.
This is called left-hand projection of a tree. So, to simplify:
- Select one node per level.
- The node chosen is the first one on that level.
- The number of visible nodes in the left-side projection matches the tree’s height, as one node is taken from each level.
Examples
Example 1
graph TD A(1) A --- B(2) & C(3) & D(4) B --- E(5) & F(6) C --- G(7) G --- H(8) & I(9) I --- J(10)
|
|
Solution
Method 1 - BFS
To solve this problem:
- We need to traverse the tree level by level (breadth-first search) and collect the first node from each level.
- A first traversal of the tree ensures visibility from the left side.
- This boils down to a simple BFS but paying attention to leftmost visibility at each level.
Approach
- Use a queue structure to perform a level-order traversal of the tree:
- Start from the root.
- Process each level and ensure the first node at each level is added to the result list.
- For each level:
- Push all children of that node to the queue.
- Record the value of the leftmost node only.
- Return the accumulated list.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n)
. Every node is visited once in a BFS. - 🧺 Space complexity:
O(w)
. The maximum space is the width of the tree at its widest level, which is proportional to the number of nodes at a level.