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.
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).
- Process the tree level by level.
- For each level, the last node in the queue (before moving to the next level) is the rightmost node.
- 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 deque23def rightSideView(root):4 if not root: return []56 queue = deque([root])7 result = []89 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 result14 if i == level_size - 1:15 result.append(node.val)1617 if node.left: queue.append(node.left)18 if node.right: queue.append(node.right)1920 return result
Complexity Analysis
- Time Complexity: O(N).
- Space Complexity: O(D) (Diameter/Width of tree).
ON THIS PAGE
- Problem Understanding
- Algorithm Strategy
- Interactive Visualization
- Dry Run
- Edge Cases & Common Mistakes
- Solution Code
- Complexity Analysis
