Tensorum
YouTubeशिकायला सुरुवात करा
LeetCode 112 · Root-to-Leaf Paths

Path Sum

LeetCode 112 · सोपा · उपाय, intuition आणि टप्प्याटप्प्याने वॉकथ्रू

Reduce the target; check at leaves.

सोपाTreeDepth-First SearchBreadth-First SearchBinary Tree

मी 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. 1

    None → False.

  2. 2

    targetSum −= node.val.

  3. 3

    Leaf → targetSum == 0.

  4. 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.