# Definition for a binary tree node.
# 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: TreeNode, sum: int) -> int:
res, target = 0, sum
def dfs(node, suffix_sum, suffix_mapping, path):
if node is None:
return
val = node.val
suffix_sum += val
former = suffix_sum - target
if former in suffix_mapping:
nonlocal res
res += suffix_mapping[former]
suffix_mapping[suffix_sum] = suffix_mapping.get(suffix_sum, 0) + 1
path.append(val)
dfs(node.left, suffix_sum, suffix_mapping, path)
dfs(node.right, suffix_sum, suffix_mapping, path)
suffix_mapping[suffix_sum] = suffix_mapping[suffix_sum] - 1
if suffix_mapping[suffix_sum] == 0:
del suffix_mapping[suffix_sum]
path.pop()
dfs(root, 0, {0: 1}, [])
return res