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.