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
2?3541πŸ“ΈRight Side ViewVisible rooms (rightmost): Floor 2β†’3, Floor 1β†’4, Groundβ†’1Result: [1, 3, 4] (top to bottom)
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

n
2n
βœ“ Linear Growth
Space Complexity
O(w)

Queue stores at most the maximum width of tree (nodes at one level)

n
2n
βœ“ 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
Asked in
Meta 42 Amazon 38 Microsoft 31 Google 28
186.5K Views
High Frequency
~15 min Avg. Time
8.9K Likes
Ln 1, Col 1
Smart Actions
πŸ’‘ Explanation
AI Ready
πŸ’‘ Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen