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.