时间复杂度(O(n^2),思想:后序遍历+动态规划
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
count = 0
def update_dict(self, dict1, dict2, value, targe_sum):
for key in dict1:
curr_value = key + value
if curr_value not in dict2:
dict2[curr_value] = dict1[key]
else:
dict2[curr_value] += dict1[key]
dict1_value = targe_sum-value
if dict1_value in dict1:
self.count += dict1[dict1_value]
def pathCount(self, root: TreeNode, target_sum: int) -> dict():
if root == None: return {}
curr_left_map = self.pathCount(root.left, target_sum)
curr_right_map = self.pathCount(root.right, target_sum)
curr_map2 = {}
self.update_dict({0: 1}, curr_map2, root.val, target_sum)
self.update_dict(curr_left_map, curr_map2, root.val, target_sum)
self.update_dict(curr_right_map, curr_map2, root.val, target_sum)
del curr_left_map, curr_right_map
return curr_map2
def pathSum(self, root: TreeNode, sum: int) -> int:
self.pathCount(root, sum)
return self.count