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
LeetCode-এ খুলুন ↗

আমি 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.