Python Iterative solution
This problem is similar to 560: Subarray Sum Equals K.\nTo prevent extra copy, use a backtrack flag to control the sum_d .\n\n\nimport collections\n\nclass Solu
This problem is similar to 560: Subarray Sum Equals K.\nTo prevent extra copy, use a backtrack flag to control the sum_d .\n\n```\nimport collections\n\nclass Solution:\n    def pathSum(self, root: TreeNode, sum: int) -> int:     \n        if not root:\n            return 0\n        \n        target = sum\n        path_sum_cnt = 0   \n        sum_d = collections.defaultdict(int)\n        sum_d[0] = 1\n        \n        stack = [(root, 0, False)]\n        while stack:\n            node, cur_sum, backtrack = stack.pop()\n            if backtrack:\n                sum_d[cur_sum] -= 1\n                continue\n              \n            cur_sum += node.val\n            # prev_sum + target = cur_sum\n            path_sum_cnt += sum_d[cur_sum - target]\n            \n            sum_d[cur_sum] += 1\n            stack.append((None, cur_sum, True))\n            if node.left:\n                stack.append((node.left, cur_sum, False))\n                \n            if node.right:\n                stack.append((node.right, cur_sum, False))\n                \n        return path_sum_cnt\n```
['Iterator', 'Python']