Binary Tree Right Side View
Problem
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.
Examples
Example 1
Input: root = [1,2,3,null,5,null,4]
Output: [1, 3, 4]
Example 2
Input: root = [1,null,3]
Output: [1, 3]
Example 3
Input: root = []
Output: []
Key Insight
Level-order traversal, but only keep the last node of each level.
Right side view = last node at each level. BFS: keep last of each level. DFS: go right-first, add first node at each depth.
How to Approach This Problem
Pattern Recognition: When you see keywords like
binary tree right side view trees,
think Tree Traversal.
Step-by-Step Reasoning
1
From the right side, you see:
Answer: The last node of each level
Rightmost node blocks view of nodes to its left at the same level.
2
To find the last node of each level:
Answer: Level-order (BFS)
BFS processes levels left-to-right. Last node processed in each level is the answer.
3
With DFS, we can also solve this by:
Answer: Visiting right child before left
If we go right-first, the first node we see at each depth is the rightmost. Track first visit per depth.
4
Using BFS, we keep:
Answer: Last node of each level
The last one we process before moving to next level is the rightmost.
5
In right-first DFS, we add a node to result when:
Answer: It's the first node we see at its depth
First node at each depth (with right-first traversal) is the rightmost. Track depths we've seen.
6
The result should be ordered:
Answer: By depth (top to bottom)
"From top to bottom" = depth 0, 1, 2, ... which is natural BFS/DFS order.
Solution
from collections import deque
def rightSideView(root: TreeNode) -> List[int]:
if not root:
return []
result = []
queue = deque([root])
while queue:
level_size = len(queue)
for i in range(level_size):
node = queue.popleft()
# Last node in this level
if i == level_size - 1:
result.append(node.val)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
return result
Complexity Analysis
| Time | O(n) |
|---|---|
| Space | O(w) |
Master This Pattern
Build intuition with interactive MCQs. Practice Tree Traversal problems in the LeetEye app.
Download LeetEye Free