Coding Interview PatternsBinary Tree Right Side View
MediumTree Depth-First Search
Binary Tree Right Side View
Explanation & Solution
Description
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:
```tree
[1, 2, 3, null, 5, null, 4]
`
Input:root = [1, 2, 3, null, 5, null, 4]
0
1
1
2
2
3
3
null
4
5
5
null
6
4
Output:[1, 3, 4]
0
1
1
3
2
4
Explanation: From the right side, you see node 1 at level 0, node 3 at level 1, and node 4 at level 2.
Example 2:
```tree
[1, null, 3]
`
Input:root = [1, null, 3]
0
1
1
null
2
3
Output:[1, 3]
0
1
1
3
Example 3:
Input: root = []
Output: []
Constraints
- The number of nodes in the tree is in the range
[0, 100] -100 <= Node.val <= 100
Approach
Tree Depth-First Search pattern
1. Handle Empty Tree
- If
rootisnull: - Return
[]
2. Initialize BFS
- Create
result = []for the right-side view values - Create
queue = [root]withhead = 0for efficient dequeue
3. Process Level by Level
- While the queue is not empty:
- Calculate
levelSize = queue.length - head - This tells us how many nodes are on the current level
4. Find the Rightmost Node
- Loop through all nodes in the current level:
- Dequeue via
queue[head++] - If this is the last node in the level (
i === levelSize - 1): - Push its value to
result - Enqueue left and right children
5. Why the Last Node?
- BFS processes nodes left to right
- The last node at each level is the rightmost node
- That is the node visible from the right side
6. Return Result
- After all levels, return
result - Contains one value per level — the rightmost node's value
Key Insight
- Standard BFS level-by-level traversal
- Only keep the last node from each level
- A left-side-only subtree can still appear in the right side view if the right subtree is shorter
Time
O(n)visit each node onceSpace
O(n)queue holds at most one level of nodesVisualization
Input:
DFS Traversal[1, 2, 3, 5, 4]
output0
Press play to start DFS traversal
CurrentIn stackComplete
11 steps