思路:
一:
# 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 findPath(self, root, sum): # 找到以root为起点的满足条件的路径
result = 0
if not root:
return result
if root.val == sum:
result += 1
result += self.findPath(root.left, sum - root.val)
result += self.findPath(root.right, sum - root.val)
return result
def pathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: int
"""
result = 0
if not root:
return result
result += self.findPath(root, sum)
result += self.pathSum(root.left, sum)
result += self.pathSum(root.right, sum)
return result
二、
def pathSum(self, root, sum):
def dfs(node, s, n_used):
count = 0
if node is None:
return 0
if node.val == s:
count += 1
count += dfs(node.left, s - node.val, True)
count += dfs(node.right, s - node.val, True)
if not n_used:
count += dfs(node.left, s, False)
count += dfs(node.right, s, False)
return count
return dfs(root, sum, False)
参考:https://blog.csdn.net/qq_40155090/article/details/84563865