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.