-
-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy path0437-path-sum-iii.py
More file actions
49 lines (38 loc) · 1.19 KB
/
0437-path-sum-iii.py
File metadata and controls
49 lines (38 loc) · 1.19 KB
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
# time complexity: O(n)
# space complexity: O(n)
from collections import defaultdict
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 pathSum(self, root: Optional[TreeNode], targetSum: int) -> int:
def traverse(node: TreeNode, currSum: int):
nonlocal count
if node is None:
return
currSum += node.val
if currSum == targetSum:
count += 1
count += prefixHash[currSum - targetSum]
prefixHash[currSum] += 1
traverse(node.left, currSum)
traverse(node.right, currSum)
prefixHash[currSum] -= 1
count = 0
prefixHash = defaultdict(int)
traverse(root, 0)
return count
root = TreeNode(10)
root.left = TreeNode(5)
root.left.left = TreeNode(3)
root.left.left.left = TreeNode(3)
root.left.left.right = TreeNode(-2)
root.left.right = TreeNode(2)
root.left.right.right = TreeNode(1)
root.right = TreeNode(-3)
root.right.right = TreeNode(11)
targetSum = 8
print(Solution().pathSum(root, targetSum))