Solve 112. Path Sum
This commit is contained in:
parent
85af04c566
commit
cef4a48ca9
17
python/112_path_sum.py
Normal file
17
python/112_path_sum.py
Normal 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)
|
Loading…
Reference in New Issue
Block a user