Problem
You are given the root of an n-ary tree, where each node may have multiple children. Imagine yourself standing on the right side of the tree. Write a program to return a list of the values of the nodes visible from the right side, ordered from top to bottom.
This is called right-hand projection of a tree. So, to simplify:
- At each level of the tree, we select only one node.
- The node chosen is the last one on that level.
- The number of nodes visible in the right-hand projection matches the height of the tree, as one node is picked per 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 determine the right side view, you need to traverse the tree level-by-level (often referred to as a breadth-first search or BFS). At each level:
- Look at the last node (the right-most node) in that level.
- Collect these nodes as they represent the right side view of the tree.
This works because the right-most node in a level is visible when viewed from the right side.
Approach
- Use a queue (BFS) to traverse the tree level-by-level.
- For each level:
- Identify the right-most node of the level (last node traversed).
- Collect these right-most nodes in a result list and return it.
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.