:type root: TreeNode :type sum: int :rtype: bool
(self, root, sum)
| 33 | |
| 34 | class Solution(object): |
| 35 | def hasPathSum(self, root, sum): |
| 36 | """ |
| 37 | :type root: TreeNode |
| 38 | :type sum: int |
| 39 | :rtype: bool |
| 40 | """ |
| 41 | if not root: |
| 42 | return False |
| 43 | |
| 44 | def helper(prev, root, sum): |
| 45 | if prev + root.val == sum: |
| 46 | if not root.left and not root.right: |
| 47 | return True |
| 48 | |
| 49 | if root.left: |
| 50 | if helper(prev + root.val, root.left, sum): |
| 51 | return True |
| 52 | |
| 53 | if root.right: |
| 54 | if helper(prev + root.val, root.right, sum): |
| 55 | return True |
| 56 | |
| 57 | return False |
| 58 | |
| 59 | return helper(0, root, sum) |