437. Path Sum III

Given the root of a binary tree and an integer targetSum, return the number of paths where the sum of the values along the path equals targetSum.

The path does not need to start or end at the root or a leaf, but it must go downwards (i.e., traveling only from parent nodes to child nodes).

def pathSum(self, root: Optional[TreeNode], targetSum: int) -> int: 
    res = 0 
    h = collections.defaultdict(int) 
    h[0] = 1 
     
    def preorder(node, s): 
        nonlocal res 
        cur_sum = s + node.val 
         
        res += h[cur_sum - targetSum] 
         
        h[cur_sum] += 1 
        if node.left: 
            preorder(node.left, cur_sum) 
        if node.right: 
            preorder(node.right, cur_sum) 
        h[cur_sum] -= 1 
     
    if not root: 
        return 0 
     
    preorder(root, 0) 
     
    return res