Data Structures & Algorithms Binary Trees
💡
Exercise 93

Right Side View 20 XP Medium

LeetCode Ctrl+Enter Run Ctrl+S Save

Imagine standing on the right side of a binary tree. Return the values of the nodes you can see, ordered from top to bottom.

# 1 ← you see 1 # / \ # 2 3 ← you see 3 # \ \ # 5 4 ← you see 4 # Right side view: [1, 3, 4]

This is a BFS variation — at each level, the last node is what you see from the right:

  • Do a normal level-order traversal (BFS)
  • At each level, keep only the last value
  • Alternatively: use DFS visiting right child first at each depth

Time: O(n), Space: O(n). A simple twist on level-order traversal!

📋 Instructions
Implement `right_side_view(root)` using BFS. Test with the tree above.
Do level-order BFS. At each level, the last node processed (level[-1]) is visible from the right side. Collect these into the result.
🧪 Test Cases
Input
right_side_view(root)
Expected
[1, 3, 4]
Test case 1
Input
right_side_view(TreeNode(1, TreeNode(2)))
Expected
[1, 2]
Test case 2
main.py
Hi! I'm Rex 👋
Output
Ready. Press ▶ Run or Ctrl+Enter.