Solve 112. Path Sum

This commit is contained in:
ktkovachev 2024-04-08 18:18:54 +01:00 committed by GitHub
parent 85af04c566
commit cef4a48ca9
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

17
python/112_path_sum.py Normal file
View File

@ -0,0 +1,17 @@
# 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:
def hasPathSumInner(root: Optional[TreeNode], currentSum: int) -> bool:
if root is None:
return False
elif root.left is None and root.right is None:
return currentSum + root.val == targetSum
else:
newSum = currentSum + root.val
return hasPathSumInner(root.left, newSum) or hasPathSumInner(root.right, newSum)
return hasPathSumInner(root, 0)