Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # 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:
- # Base case if "after" leaf node
- if not root:
- return False
- # Update target sum to subtract current node's value
- newTargetSum = targetSum - root.val
- # Base case if reached leaf node
- if not root.left and not root.right:
- # Normal case: Return True if path found
- if newTargetSum == 0:
- return True
- # Normal case: Return False if path not found
- return False
- # Return if there is a path in the left subtree or a path in the right subtree
- return self.hasPathSum(root.left, newTargetSum) or self.hasPathSum(root.right, newTargetSum)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement