Introduction
Right Side View means:
- viewing binary tree
- from right side
Goal:
- return last visible node
from every level
Example:
1
/ \
2 3
\ \
5 4
Right Side View:1 3 4
Explanation:
At every level, the rightmost node becomes visible. This problem is one of the most important applications of:
BFS TraversalConstraints
1 <= Number of Nodes <= 10^5Approach : Queue Based BFS Solution
Explanations:
Explanation:
The idea is:
- traverse tree level by level
- store last node of every level
Steps:
- Push root into queue.
- Process current level.
- Track last node.
- Push child nodes.
- Store rightmost node.
- Repeat until queue becomes empty.
This approach:
- uses queue
- follows BFS traversal
- processes levels independently
Dry Run
Level 1:
1
Rightmost:
1
Level 2:
2 3
Rightmost:
3
Level 3:
5 4
Rightmost:
4
Output:1 3 4
Practice :
Complexity Analysis :
Time Complexity:- O(n)Explanation : Every tree node is visited once.
Space Complexity:- O(n)
Explanation : Queue stores tree nodes level wise.
Why This Problem is Important