4/22/2021

[LeetCode] 437. Path Sum III

 Problem : https://leetcode.com/problems/path-sum-iii/

Traval tree in preorder approach. And use prefix-sum to find number of sub-array node value can form the target sum.


# 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, targetSum: int) -> int:
        self.result = 0
        
        
        def dfs(node, preSum, seen):
            if node:
                preSum += node.val
                self.result += seen[preSum - targetSum]
                
                seen[preSum] += 1
                
                dfs(node.left, preSum, seen)
                dfs(node.right, preSum, seen)
                    
                seen[preSum] -= 1
        
        
        seen = defaultdict(int)
        seen[0] = 1
        dfs(root, 0, seen)
        return self.result

No comments:

Post a Comment