问题描述:

给定一个二叉树,它的每个结点都存放着一个整数值。

找出路径和等于给定数值的路径总数。

路径不需要从根节点开始,也不需要在叶子节点结束,但是路径方向必须是向下的(只能从父节点到子节点)。

二叉树不超过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

最新文章

  1. 【实例】html5-canvas中实现背景图片的移动
  2. 【 D3.js 入门系列 --- 3 】 做一个简单的图表!
  3. hdu 5284 BestCoder Round #48 ($) 1001 水题 *
  4. FlashPlayer for Android
  5. cocos2dx 碰撞检测
  6. CloudStack API编程指引
  7. (原)调用jpeglib对图像进行压缩
  8. Mac编程的官方文档(类似MSDN)
  9. FRAM 铁电存储器
  10. ArcGIS三种方式打断相交线------拓扑法
  11. 利用模板template动态渲染jsp页面
  12. Ubuntu12.04下安ns-3.29及Ubuntu换源方法
  13. linux内核里的字符串转换 ,链表操作常用函数(转)
  14. call()和apply()
  15. SDL源码阅读笔记(2) video dirver的初始化及选择
  16. Domination(概率DP)
  17. python学习day3 编程语言分类 变量 格式化输出
  18. jsp 中出现大量红线,而且页面能正常访问
  19. RabbitMQ之集群搭建
  20. Angular6 学习笔记——组件详解之模板语法

热门文章

  1. 经典算法分析:n与lgn
  2. ZOJ 3963 Heap Partition(multiset + stl自带二分 + 贪心)题解
  3. 【做题】arc080_f-Prime Flip——转换、数论及匹配
  4. (转)JPA & Restful
  5. p3792 由乃与大母神原型和偶像崇拜(思维+线段树)
  6. 《计算机网络》-CCNA命令大全
  7. (转) Face-Resources
  8. 关不掉.vbs
  9. 【译】第37节---EF6-异步查询和保存
  10. HDU 1403 Longest Common Substring(最长公共子串)