问题描述:
给定一个二叉树,它的每个结点都存放着一个整数值。
找出路径和等于给定数值的路径总数。
路径不需要从根节点开始,也不需要在叶子节点结束,但是路径方向必须是向下的(只能从父节点到子节点)。
二叉树不超过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
方法1:
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)
方法2:
class Solution(object):
def pathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: int
"""
self.sum=sum
self.result=0
self.d={0:1}
self.f(root,0)
return(self.result) def f(self,root,csum):
if(root!=None):
csum+=root.val
if((csum-self.sum) in self.d):
self.result+=self.d[csum-self.sum]
if(csum in self.d):
self.d[csum]+=1
else:
self.d[csum]=1
self.f(root.left,csum)
self.f(root.right,csum)
self.d[csum]-=1
方法3:
class Solution(object):
def pathSum(self, root, target):
"""
:type root: TreeNode
:type target: int
:rtype: int
"""
self.count = 0
preDict = {0: 1}
def dfs(p, target, pathSum, preDict):
if p:
pathSum += p.val
self.count += preDict.get(pathSum - target, 0)
preDict[pathSum] = preDict.get(pathSum, 0) + 1
dfs(p.left, target, pathSum, preDict)
dfs(p.right, target, pathSum, preDict)
preDict[pathSum] -= 1
dfs(root, target, 0, preDict)
return self.count
2018-10-02 20:04:13