Binary Tree Right Side View - Problem
Imagine you're standing on the right side of a binary tree, looking at it from that perspective. You can only see certain nodes - specifically, the rightmost node at each level.
Given the root of a binary tree, return the values of the nodes you can see when viewing the tree from the right side, ordered from top to bottom.
For example, if you have a tree where level 0 has node 1, level 1 has nodes 2 and 3, and level 2 has node 5 under node 2, then from the right side you would see: [1, 3, 5] - the rightmost node at each level.
Input & Output
example_1.py β Standard Binary Tree
$
Input:
root = [1,2,3,null,5,null,4]
βΊ
Output:
[1,3,4]
π‘ Note:
From the right side: Level 0 shows node 1, Level 1 shows node 3 (rightmost), Level 2 shows node 4 (rightmost)
example_2.py β Right-Heavy Tree
$
Input:
root = [1,null,3]
βΊ
Output:
[1,3]
π‘ Note:
Only has right children, so we see node 1 at level 0 and node 3 at level 1
example_3.py β Single Node
$
Input:
root = [1]
βΊ
Output:
[1]
π‘ Note:
Only one node exists, so the right side view contains just that node
Visualization
Tap to expand
Understanding the Visualization
1
Position Camera
Stand on the right side of the building (tree) with your camera
2
Capture Each Floor
For each floor (level), only the rightmost room (node) is visible
3
Smart Strategy
Instead of checking every room, explore right corridors first - the first room you find on each new floor is automatically the rightmost!
Key Takeaway
π― Key Insight: By exploring the building right-first (DFS with right child priority), the first room you discover on each new floor is guaranteed to be the rightmost room visible from the outside!
Time & Space Complexity
Time Complexity
O(n)
Visit each node exactly once during BFS traversal
β Linear Growth
Space Complexity
O(w)
Queue stores at most the maximum width of tree (nodes at one level)
β Linear Space
Constraints
- The number of nodes in the tree is in the range [0, 100]
- Node values are in the range [-100, 100]
- Tree height will not exceed 100 levels
π‘
Explanation
AI Ready
π‘ Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code