Path Sum
LeetCode 112 · సులభం · పరిష్కారం, intuition & దశలవారీ వాక్త్రూ
Reduce the target; check at leaves.
నేను Path Sum (LeetCode 112) ను ఇలా పరిష్కరించాను — Root-to-Leaf Paths ప్యాటర్న్లోని ఒక సులభం ప్రాబ్లమ్. కింద: intuition, దశలవారీ approach, నా accepted Python కోడ్, animated test cases, line-by-line debugger.
కింది వివరణ ఇంగ్లీష్లో ఉంది.
Intuition
Subtract each node's value from the target on the way down. At a leaf, the path works exactly when what's left is zero.
Approach
- 1
None → False.
- 2
targetSum −= node.val.
- 3
Leaf → targetSum == 0.
- 4
Otherwise try left or right.
నేను ఎలా పరిష్కరించాను
DFS with remaining sumPythonO(n) time · O(h) space
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:
if root==None:
return False
#reduce target sum
targetSum = targetSum-root.val
if root.left==None and root.right==None:
return targetSum==0
return self.hasPathSum(root.left,targetSum) or self.hasPathSum(root.right,targetSum)Path Sum — తరచూ అడిగే ప్రశ్నలు
Path Sum వెనుక ఉన్న intuition ఏమిటి?
Subtract each node's value from the target on the way down. At a leaf, the path works exactly when what's left is zero.
Path Sum (LeetCode 112) ను ఎలా పరిష్కరించాలి?
1. None → False. 2. targetSum −= node.val. 3. Leaf → targetSum == 0. 4. Otherwise try left or right.
Path Sum యొక్క time, space complexity ఎంత?
Time: O(n). Space: O(h). (Accepted approach: DFS with remaining sum.)
Path Sum లో సాధారణ పొరపాట్లు ఏమిటి?
Only leaf-to-root paths count — an internal node hitting zero isn't enough.