Binary Tree Right Side View
LeetCode 199 · మధ్యస్థం · పరిష్కారం, intuition & దశలవారీ వాక్త్రూ
Right-first DFS; record the first node per level.
నేను Binary Tree Right Side View (LeetCode 199) ను ఇలా పరిష్కరించాను — BFS / Level Order ప్యాటర్న్లోని ఒక మధ్యస్థం ప్రాబ్లమ్. కింద: intuition, దశలవారీ approach, నా accepted Python కోడ్, animated test cases, 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.
నేను ఎలా పరిష్కరించాను
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 — తరచూ అడిగే ప్రశ్నలు
Binary Tree Right Side View వెనుక ఉన్న 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.
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.
Binary Tree Right Side View యొక్క time, space complexity ఎంత?
Time: O(n). Space: O(h). (Accepted approach: Right-first DFS.)
Binary Tree Right Side View లో సాధారణ పొరపాట్లు ఏమిటి?
A left-only branch deeper than the right side is still visible.