6/22/2020

[LeetCode] 112. Path Sum

Problem : https://leetcode.com/problems/path-sum/

Be careful, the problem statement requires the path must end at leaf node.
Node values and the target value may be negative.
# Definition for a binary tree node.
# 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: TreeNode, targetSum: int) -> bool:
        
        def dfs(node, sums):
            if node:
                sums += node.val
                if not node.left and not node.right:
                    yield sums
                else:
                    if node.left: yield from dfs(node.left, sums)
                    if node.right: yield from dfs(node.right, sums)
        
        return any(sums == targetSum for sums in dfs(root, 0))

Edited on 04/22/2021. Update DFS solution by using 'yield' and 'yield from'.

No comments:

Post a Comment