E-112. Path Sum

# 0 O(n), O(n)
class Solution:
    def hasPathSum(self, root: TreeNode, sum: int) -> bool:
        def check_sum_helper(root, cur_sum, target_sum):
            if not root:
                return False
            if not root.right and not root.left:
                cur_sum = root.val + cur_sum
                if cur_sum == target_sum:
                    return True
                else:
                    return False
            cur_sum = root.val + cur_sum
            return check_sum_helper(root.left, cur_sum, target_sum) or check_sum_helper(root.right, cur_sum, target_sum)
        
        if not root:
            return False
        return check_sum_helper(root, 0, sum)

# 1 不用helper的lc标答, 写的还挺好的:
class Solution:
    def hasPathSum(self, root: TreeNode, sum: int) -> bool:
        if not root:
            return False
        sum -= root.val
        
        if not root.right and not root.left:
            return sum == 0
        
        return self.hasPathSum(root.left, sum) or self.hasPathSum(root.right, sum)

Last updated

Was this helpful?