[LC] 437. Path Sum III

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

Solution 1:
Time: O(N^2)
Space: O(Height)
 1 # Definition for a binary tree node.
 2 # class TreeNode:
 3 #     def __init__(self, x):
 4 #         self.val = x
 5 #         self.left = None
 6 #         self.right = None
 7 
 8 class Solution:
 9     def pathSum(self, root: TreeNode, sum: int) -> int:
10         if root is None:
11             return 0
12         cur = self.helper(root, sum) 
13         left = self.pathSum(root.left, sum) 
14         right = self.pathSum(root.right, sum)
15         return cur + left + right
16     
17     def helper(self, root, sum):
18         if root is None:
19             return 0
20         left = self.helper(root.left, sum - root.val)
21         right = self.helper(root.right, sum - root.val)
22         if sum == root.val:
23             return 1 + left + right
24         return left + right

 

Solution 2:

Time: O(N)

Space: O(N)

 1 # Definition for a binary tree node.
 2 # class TreeNode:
 3 #     def __init__(self, x):
 4 #         self.val = x
 5 #         self.left = None
 6 #         self.right = None
 7 
 8 class Solution:
 9     def pathSum(self, root: TreeNode, sum: int) -> int:
10         if root is None:
11             return 0
12         self.res = 0
13         # initilized with 0 as prefix instead of empty b/c need to conver path coming from root
14         my_dict = {0 : 1}
15         self.helper(root, sum, 0, my_dict) 
16         return self.res
17     
18     def helper(self, root, sum, cur_sum, my_dict):
19         if root is None:
20             return
21         cur_sum += root.val
22         reminder = cur_sum - sum
23         # use reminder as key
24         if reminder in my_dict: 
25             self.res += my_dict[reminder]
26         my_dict[cur_sum] = my_dict.get(cur_sum, 0) + 1
27         # pass cur_sum to children
28         left = self.helper(root.left, sum, cur_sum, my_dict)
29         right = self.helper(root.right, sum, cur_sum, my_dict)
30         my_dict[cur_sum] -= 1

 

你可能感兴趣的:([LC] 437. Path Sum III)