-
Notifications
You must be signed in to change notification settings - Fork 0
/
path_sum.py
56 lines (43 loc) · 1.63 KB
/
path_sum.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
"""
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.
A leaf is a node with no children.
"""
from typing import Optional
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:
"""
Determine if there is a root to leaf path in the binary tree that sums up to targetSum.
Args:
- root : root node of binary tree
- targetSum : an int representing targetSum
Returns:
- a boolean value
"""
# if root node is None, there is no path that sums up to targetSum
if not root:
return False
# if root node is a leaf node and its value equals targetSum return True
if not root.left and not root.right and targetSum == root.val:
return True
# recursively check the left and right subtrees for paths that sum up to targetSum
left = self.hasPathSum(root.left, targetSum - root.val)
right = self.hasPathSum(root.right, targetSum - root.val)
return left or right
root = TreeNode(5)
root.left = TreeNode(4)
root.right = TreeNode(8)
root.left.left = TreeNode(11)
root.left.left.left = TreeNode(7)
root.left.left.right = TreeNode(2)
root.right.left = TreeNode(13)
root.right.right = TreeNode(4)
root.right.right.right = TreeNode(1)
sol = Solution()
targetSum = 22
print(sol.hasPathSum(root,targetSum))