|
| 1 | +# https://leetcode.com/problems/path-sum/ |
| 2 | +''' |
| 3 | +Given the root of a binary tree and an integer targetSum, return true if the tree has a root-to-leaf path such that adding up all the values along the path equals targetSum. |
| 4 | +Solution: O(N) Time and O(Height) Space |
| 5 | +''' |
| 6 | + |
| 7 | +class Solution: |
| 8 | + def hasPathSum(self, root: TreeNode, targetSum: int) -> bool: |
| 9 | + def solve(root, sums): |
| 10 | + if root is None: |
| 11 | + return False |
| 12 | + |
| 13 | + if root.left is None and root.right is None and root.val == sums: |
| 14 | + return True |
| 15 | + sums -= root.val |
| 16 | + return solve(root.left, sums) or solve(root.right, sums) |
| 17 | + |
| 18 | + |
| 19 | + res = solve(root, targetSum) |
| 20 | + return res |
0 commit comments