题目:
给定一棵二叉树,和一个目标和sum,找到该二叉树中路径和为sum的个数。样例如下
返回3,路径分别为:
解题思路:
从每个节点出发进行dfs读取,判断当前节点值是否等于目标值,不等则更新目标值(原目标值-当前节点值),相等则将返回值加一。
代码(Python):
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def pathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: int
"""
def dfs(root,sum):
if root==None:
return 0
if root.val==sum:
return 1+dfs(root.left,0)+dfs(root.right,0)
return dfs(root.left,sum-root.val)+dfs(root.right,sum-root.val)
if root==None:
return 0
return dfs(root,sum)+self.pathSum(root.left,sum)+self.pathSum(root.right,sum)