Skip to content

Commit 9fc52c4

Browse files
iamAntimPalAntim-IWPIamShiwangi
committed
Update 437. Path Sum III.py
Co-Authored-By: Antim-IWP <203163676+Antim-IWP@users.noreply.github.com> Co-Authored-By: Shiwangi Srivastava <174641070+IamShiwangi@users.noreply.github.com>
1 parent 144b3f2 commit 9fc52c4

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
# Definition for a binary tree node.
2+
# class TreeNode:
3+
# def __init__(self, val=0, left=None, right=None):
4+
# self.val = val
5+
# self.left = left
6+
# self.right = right
7+
class Solution:
8+
def pathSum(self, root: Optional[TreeNode], targetSum: int) -> int:
9+
def dfs(node, s):
10+
if node is None:
11+
return 0
12+
s += node.val
13+
ans = cnt[s - targetSum]
14+
cnt[s] += 1
15+
ans += dfs(node.left, s)
16+
ans += dfs(node.right, s)
17+
cnt[s] -= 1
18+
return ans
19+
20+
cnt = Counter({0: 1})
21+
return dfs(root, 0)

0 commit comments

Comments
 (0)