给定一个二叉树的根节点root,和一个整数targetSum,求该二叉树里节点值之和等于targetSum的路径的数目。
路径 不需要从根节点开始,也不需要在叶子节点结束,但是路径方向必须是向下的(只能从父节点到子节点)。
示例 1:
输入:root = [10,5,-3,3,2,null,11,3,-2,null,1], targetSum = 8
输出:3
解释:和等于 8 的路径有 3 条,如图所示。
示例 2:
输入:root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22
输出:3
提示:
二叉树的节点个数的范围是 [0,1000]
-10^9 <= Node.val <= 10^9
-1000 <= targetSum <= 1000
解法:DFS(深度优先搜索遍历)
参考官方题解:指路
官方题解的思路只讲了rootSum这个函数。我们需要自行注意pathSum这个函数。也就是重点注意理解以下两行代码:
ret += self.pathSum(root.left, targetSum)
ret += self.pathSum(root.right, targetSum)
代码实现:
class Solution:
def pathSum(self, root: TreeNode, targetSum: int) -> int:
def rootSum(root, targetSum):
if root is None:
return 0
ret = 0
if root.val == targetSum:
ret += 1
ret += rootSum(root.left, targetSum - root.val)
ret += rootSum(root.right, targetSum - root.val)
return ret
if root is None:
return 0
ret = rootSum(root, targetSum) #以root为根节点进行计算,也就是在这个函数里面不管怎样计算sum,都是会带上root的值
ret += self.pathSum(root.left, targetSum) #注意这里是pathSum函数,相当于是另一棵树了
ret += self.pathSum(root.right, targetSum)
return ret