Browse Curriculum
FAANGPrep Sprint
Medium

Binary Tree Rightmost Node (Right Side View)

Return the values of the nodes you can see ordered from top to bottom.
10 min
Time: O(n)
Space: O(1)
Solve on LeetCode

Problem Understanding

Given the root of a binary tree, imagine yourself standing on the right side of it. Return the values of the nodes you can see ordered from top to bottom.

  • Essentially: For every level, pick the last node.

Algorithm Strategy

We can use BFS (Level Order Traversal).

  1. Process the tree level by level.
  2. For each level, the last node in the queue (before moving to the next level) is the rightmost node.
  3. Add that node's value to our result list.

Interactive Visualization

Step 1 / 1
Empty Heap

Initializing...

1x

Watch BFS collecting the last element of every level.

Dry Run

Tree: Root 1 -> Left 2, Right 3 -> 2 has Right 5, 3 has Right 4.

Level Nodes Rightmost Result
0 [1] 1 [1]
1 [2, 3] 3 [1, 3]
2 [5, 4] 4 [1, 3, 4]

Edge Cases & Common Mistakes

Edge Cases:

  • Null Root: Return [].
  • Left-skewed Tree: You still see the left nodes if there are no right nodes blocking them (Right Side View != Right Children only!).

Common Mistakes:

  • Only traversing node.right. (Wrong! You might see left children if the right side is shorter).

Solution Code

BFS approach.

1from collections import deque
2
3def rightSideView(root):
4 if not root: return []
5
6 queue = deque([root])
7 result = []
8
9 while queue:
10 level_size = len(queue)
11 for i in range(level_size):
12 node = queue.popleft()
13 # If it's the last node in level, add to result
14 if i == level_size - 1:
15 result.append(node.val)
16
17 if node.left: queue.append(node.left)
18 if node.right: queue.append(node.right)
19
20 return result

Complexity Analysis

  • Time Complexity: O(N).
  • Space Complexity: O(D) (Diameter/Width of tree).