给定一个二叉树,它的每个结点都存放着一个整数值。
找出路径和等于给定数值的路径总数。
路径不需要从根节点开始,也不需要在叶子节点结束,但是路径方向必须是向下的(只能从父节点到子节点)。
二叉树不超过1000个节点,且节点数值范围是 [-1000000,1000000] 的整数。
示例:
root = [10,5,-3,3,2,null,11,3,-2,null,1], sum = 8
10
/ \
5 -3
/ \ \
3 2 11
/ \ \
3 -2 1
返回 3。和等于 8 的路径有:
1. 5 -> 3
2. 5 -> 2 -> 1
3. -3 -> 11
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/path-sum-iii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解题思路:
遍历每个节点,记录从根节点到当前节点的路径值,将当前节点作为路径终点,依次计算每个祖先节点到当前节点的路径和,如果路径和等于sum,路径数加1。
class Solution(object):
def pathSum(self, root, sum):
listPathVal = 1000 * [0]
return self.getPathCount(root, sum, listPathVal, 0)
def getPathCount(self, root, sum, listPathVal, iDepth):
if root==None:
return 0
listPathVal[iDepth] = root.val
iPathCount = 0
pathSum = 0
for i in range(iDepth, -1, -1):
pathSum += listPathVal[i]
if pathSum==sum:
iPathCount+=1
iPathCount += self.getPathCount(root.left, sum, listPathVal, iDepth+1)
iPathCount += self.getPathCount(root.right, sum, listPathVal, iDepth+1)
return iPathCount

本文探讨了在二叉树中寻找路径和等于特定数值的所有路径的问题,介绍了一种有效的递归算法,该算法能够遍历树的每个节点,计算从任意节点到其他节点的路径和,以确定路径总数。

1158

被折叠的 条评论
为什么被折叠?



