问题描述:

You are given a binary tree in which each node contains an integer value.

Find the number of paths that sum to a given value.

The path does not need to start or end at the root or a leaf, but it must go downwards (traveling only from parent nodes to child nodes).

The tree has no more than 1,000 nodes and the values are in the range -1,000,000 to 1,000,000.

Example:

root = [10,5,-3,3,2,null,11,3,-2,null,1], sum = 8

      10
/ \
5 -3
/ \ \
3 2 11
/ \ \
3 -2 1 Return 3. The paths that sum to 8 are: 1. 5 -> 3
2. 5 -> 2 -> 1
3. -3 -> 11

思路:

仍然是深度优先遍历的原则,该方法需要多做题多巩固啊!!占了我一整天时间的一道题。

从头到尾遍历每一个节点,记录从根节点到每一个节点的sum。

通过查找当前节点和目标sum之间的差值,进行相应剪枝动作

当退出当前层次时候,需要减去当前层次计算出来的和,故每次return之前都有一个减一的动作

代码:

 # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None class Solution:
def pathSum(self, root: TreeNode, sum: int) -> int:
if root == None : return 0
prefix = {0:1}
return self.Calc(root,0,sum,prefix) def Calc(self,root,cursum,target,prefix):
if root == None : return 0
cursum += root.val
res = prefix.get(cursum - target,0)
prefix[cursum] = prefix.get(cursum,0) + 1
res += self.Calc(root.left,cursum,target,prefix) + self.Calc(root.right,cursum,target,prefix)
prefix[cursum] = prefix.get(cursum) - 1
return res

最新文章

  1. 以ZeroMQ谈消息中间件的设计【译文】
  2. winform总结3> 有趣的bat/winform程序完成自己的任务,然后把自己删除
  3. 关于Java占用内存的研究
  4. Python基础(二)之元组及字典
  5. [python实现设计模式]-5.迭代器模式-一起撸串嗨皮啦
  6. hdu 5291 dp+优化 ****
  7. 用verilog模拟DDS产生正弦波信号
  8. Codeforces Round #318(Div 1) 573A, 573B,573C
  9. mongodb- Java API 查询操作
  10. APIPA
  11. net spider(python 网络爬虫)
  12. hexo从零开始
  13. linux 软中断过高性能优化案例
  14. django 执行 python manage.py makemigrations 报错
  15. Python使用suds调用webservice报错解决方法:AttributeError: 'Document' object has no attribute 'set'
  16. 简单web测试流程(转载)
  17. Android 关于“NetworkOnMainThreadException”出错提示的原因及解决办法
  18. 节约内存,请使用标签页管理工具:onetab、better onetab
  19. MongoDB 记录
  20. 用shp制作geoJson格式地图数据(shp convert to geoJson)

热门文章

  1. Visual Studio Code - 在 JS 源码(TS、压缩前代码)上使用断点
  2. 《计算机程式设计》Week2 课堂笔记
  3. ementUi rules表单验证 --》Wangqi
  4. nginx-->基本使用
  5. idea 社区版本创建javaweb项目 使用tomcat
  6. Java包的使用
  7. Spark-Core RDD转换算子-Value型
  8. vscode怎么修改颜色主题里的某种颜色
  9. Eclipse解除已关联的Coding远程仓库,重新关联github上的远程仓库
  10. neo4j 基本语法笔记(全)