Binary Tree Right Side View
LeetCode 199 · Medium · solution, intuition & step-by-step walkthrough
Right-first DFS; record the first node per level.
This is how I solved Binary Tree Right Side View (LeetCode 199), a medium problem from the BFS / Level Order pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.
Intuition
Do a DFS that visits the right child before the left. The first node you reach at each depth is the one visible from the right.
Approach
- 1
dfs(node, level): None → return.
- 2
If this level has no entry yet, record node.val.
- 3
Recurse right, then left, with level + 1.
How I solved it
Right-first DFSPythonO(n) time · O(h) space
class Solution:
def rightSideView(self, root):
ds = []
def dfs(node, level):
if node is None:
return
if len(ds) == level:
ds.append(node.val)
dfs(node.right, level + 1)
dfs(node.left, level + 1)
dfs(root, 0)
return dsBinary Tree Right Side View — FAQ
What is the intuition behind Binary Tree Right Side View?
Do a DFS that visits the right child before the left. The first node you reach at each depth is the one visible from the right.
How do you solve Binary Tree Right Side View (LeetCode 199)?
1. dfs(node, level): None → return. 2. If this level has no entry yet, record node.val. 3. Recurse right, then left, with level + 1.
What is the time and space complexity of Binary Tree Right Side View?
Time: O(n). Space: O(h). (Accepted approach: Right-first DFS.)
What are common mistakes in Binary Tree Right Side View?
A left-only branch deeper than the right side is still visible.