437. Path Sum III(路径可以任意点开始,任意点结束 or. 前缀和)
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 -> 1
思路是「枚举起点 + 向下累加」:
- 内层
dfs(node, cur_sum):固定起点为node,统计有多少条向下路径和为targetSum - 外层
pathSum:把每个节点都当作一次起点,再加上左右子树的递归,共 n 个起点
代价:每个起点往下最多走 O(n),总时间 O(n²)(平衡树约 O(n log n)),空间 O(h) 递归栈。
# 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: Optional[TreeNode], targetSum: int) -> int: def dfs(root,cur_sum): if root == None: return 0 cnt = 0 if cur_sum+root.val == targetSum: cnt = 1 l = dfs(root.left,cur_sum+root.val) r = dfs(root.right,cur_sum+root.val) return l + r + cnt if root == None: return 0 a = dfs(root,0) b = self.pathSum(root.left,targetSum) c = self.pathSum(root.right,targetSum) return a+b+c
/** * Definition

https://leetcode.com/problems/path-sum-iii/discuss/141424/Python-step-by-step-walk-through.-Easy-to-understand.-Two-solutions-comparison.-%3A-)

# 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 __init__(self): self.res = 0 self.tmap = {} def pathSum(self, root: Optional[TreeNode], targetSum: int) -> int: def dfs(root,cursum,target): if root == None: return cursum += root.val sum2 = cursum - target self.res += self.tmap.get(sum2,0) self.tmap[cursum] = self.tmap.get(cursum,0) + 1 dfs(root.left,cursum,target) dfs(root.right,cursum,target) self.tmap[cursum]-=1 self.tmap[0] = 1 dfs(root,0,targetSum) return self.res

浙公网安备 33010602011771号