Advertisement
kai-rocket

Path Sum

Jul 15th, 2021
800
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.97 KB | None | 0 0
  1. # Definition for a binary tree node.
  2. # class TreeNode:
  3. #     def __init__(self, val=0, left=None, right=None):
  4. #         self.val = val
  5. #         self.left = left
  6. #         self.right = right
  7. class Solution:
  8.  
  9.     def hasPathSum(self, root: TreeNode, targetSum: int) -> bool:
  10.         # Base case if "after" leaf node
  11.         if not root:
  12.             return False
  13.        
  14.         # Update target sum to subtract current node's value
  15.         newTargetSum = targetSum - root.val
  16.        
  17.         # Base case if reached leaf node
  18.         if not root.left and not root.right:
  19.             # Normal case: Return True if path found
  20.             if newTargetSum == 0:
  21.                 return True
  22.             # Normal case: Return False if path not found
  23.             return False
  24.        
  25.         # Return if there is a path in the left subtree or a path in the right subtree
  26.         return self.hasPathSum(root.left, newTargetSum) or self.hasPathSum(root.right, newTargetSum)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement