You are given a binary tree in which each node contains an integer value.

Find the number of paths that sum to a given value.

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

The tree has no more than 1,000 nodes and the values are in the range -1,000,000 to 1,000,000.

Example:

root = [10,5,-3,3,2,null,11,3,-2,null,1], sum = 8

      10
     /  \
    5   -3
   / \    \
  3   2   11
 / \   \
3  -2   1

Return 3. The paths that sum to 8 are:

1.  5 -> 3
2.  5 -> 2 -> 1
3. -3 -> 11

Solutions

1. DFS-递归

  两层递归。

# Time Complexity: O(n^2)
# Space Complexity: O(1)
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def pathSum(self, root: TreeNode, sum: int) -> int:
        if not root:
            return 0
        
        res = self.dfs_traverse(root, sum)
        res += self.pathSum(root.left, sum)
        res += self.pathSum(root.right, sum)
        
        return res
    
    def dfs_traverse(self, root, sum):
        if not root:
            return 0
        
        res = (sum == root.val)
        cur_sum = sum - root.val
        res += self.dfs_traverse(root.left, cur_sum)
        res += self.dfs_traverse(root.right, cur_sum)

        return res
# Runtime: 992 ms, faster than 34.16% of Python3 online submissions for Path Sum III.
# Memory Usage: 15 MB, less than 6.82% of Python3 online submissions for Path Sum III.

2. 用字典记忆化

  不是很好理解。

# Time Complexity: O(n)
# Space Complexity: O(n)
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def pathSum(self, root: TreeNode, sum: int) -> int:
        self.res = 0
        memo_sum = collections.defaultdict()
        memo_sum[0] = 1
        self.dfs(root, sum, 0, memo_sum)
        return self.res
    
    def dfs(self, root, sum, cur_sum, memo_sum):
        if not root:
            return
        cur_sum += root.val
        diff = cur_sum - sum
        
        # update result and memo
        self.res += memo_sum.get(diff, 0)
        memo_sum[cur_sum] = memo_sum.get(cur_sum, 0) + 1
        
        self.dfs(root.left, sum, cur_sum, memo_sum)
        self.dfs(root.right, sum, cur_sum, memo_sum)
        
        memo_sum[cur_sum] -= 1
# Runtime: 52 ms, faster than 97.83% of Python3 online submissions for Path Sum III.
# Memory Usage: 15.1 MB, less than 6.82% of Python3 online submissions for Path Sum III.

References

  1. 437. Path Sum III
  2. Python step-by-step walk through. Easy to understand. Two solutions comparison. : )