0%

437. Path Sum III

https://leetcode.com/problems/path-sum-iii/description/

It is simlar to https://leetcode.com/problems/subarray-sum-equals-k/description/

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution:
def pathSum(self, R: Optional[TreeNode], T: int) -> int:
def f(C,S):
nonlocal ans
if C is None:
return
S+=C.val
ans+=seen[S-T]
seen[S]+=1
f(C.left,S)
f(C.right,S)
seen[S]-=1
ans=0
seen=defaultdict(int)
seen[0]=1
f(R,0)
return ans