437. Path Sum III

# 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: Optional[TreeNode], targetSum: int) -> int:
        
        self.count = 0

        def preorder(root, curSum):

            if not root:
                return 

            curSum += root.val

            # if curSum == targetSum:
            #     self.count += 1

            self.count += h[curSum - targetSum]

            h[curSum] += 1

            preorder(root.left, curSum)
            preorder(root.right, curSum)

            h[curSum] -= 1

        h = defaultdict(int)
        h[0] = 1

        preorder(root, 0)

        return self.count