LeetCode/Easy
112. Path Sum
GenieLove!
2022. 3. 25. 19:28
728x90
반응형
Python
# 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 not root or root.val is None:
return False
if self.startFind(root, targetSum, 0):
return True
return False
def startFind(self, root: Optional[TreeNode], targetSum: int,
total: int) -> bool:
if not root.left and not root.right and total + root.val == targetSum:
return True
if root.left:
if self.startFind(root.left, targetSum, total + root.val):
return True
if root.right:
if self.startFind(root.right, targetSum, total + root.val):
return True
return False
728x90
반응형