/**
* Definition for a binary tree node.
* public class TreeNode {
* public int val;
* public TreeNode left;
* public TreeNode right;
* public TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int PathSum(TreeNode root, int sum)
{
if (root == null)
{
return ;
}
return PathSumFrom(root, sum) + PathSum(root.left, sum) + PathSum(root.right, sum);
} private int PathSumFrom(TreeNode node, int sum)
{
if (node == null)
{
return ;
}
return (node.val == sum ? : )
+ PathSumFrom(node.left, sum - node.val) + PathSumFrom(node.right, sum - node.val);
}
}

https://leetcode.com/problems/path-sum-iii/#/description

补充一个python实现,使用递归:

 class Solution:
def pathSum(self, root: 'TreeNode', sum: 'int') -> 'int':
if root == None:
return
return self.pathSumWithRoot(root,sum) + self.pathSum(root.left,sum) + self.pathSum(root.right,sum) def pathSumWithRoot(self,root,sum):
if root == None:
return
ret =
if root.val == sum:
ret +=
ret += self.pathSumWithRoot(root.left,sum-root.val) + self.pathSumWithRoot(root.right,sum-root.val)
return ret

这种实现的时间复杂度是O(n^2),执行效率比较低。

再补充一个更高效的实现,使用hash表进行缓存:(如果必须符合这个时间复杂度的要求O(n),就可以当作hard级别的题目了)

 class Solution(object):
def pathSum(self, root, target):
# define global result and path
self.result =
cache = {:} # recursive to get result
self.dfs(root, target, , cache) # return result
return self.result def dfs(self, root, target, currPathSum, cache):
# exit condition
if root is None:
return
# calculate currPathSum and required oldPathSum
currPathSum += root.val
oldPathSum = currPathSum - target
# update result and cache
self.result += cache.get(oldPathSum, )
cache[currPathSum] = cache.get(currPathSum, ) + # dfs breakdown
self.dfs(root.left, target, currPathSum, cache)
self.dfs(root.right, target, currPathSum, cache)
# when move to a different branch, the currPathSum is no longer available, hence remove one.
cache[currPathSum] -=

最新文章

  1. IP地址的组成
  2. 前端构建:Less入了个门
  3. 后缀自动机&序列自动机综合
  4. GTD时间管理(3)---行动容器分析理论法
  5. error LNK2005 new,delete 等已经在LIBCMT.lib(delete.obj) 中定义 错误修正
  6. aspx页面记住密码
  7. Vue + element-ui
  8. Caused by: java.lang.IllegalArgumentException: 'dataSource' or 'jdbcTemplate' is required
  9. 键盘上的"整蛊专家",如何防止短信轰炸机
  10. iOS 新建xib文件时,最外层view的约束问题
  11. cookiejar
  12. hdu 4506 快速幂
  13. intellij与eclipse默认快捷键对比
  14. 使用plot_importance绘制特征重要性曲线
  15. ffmpeg 视频 转 gif
  16. java.math.*;(一)
  17. visual tudio 2017--发布
  18. python 字符串的I/O 操作
  19. 论坛遇到附件上传失败问题总结(discuz)
  20. linux Posix 信号量 二

热门文章

  1. Android & iOS 启动画面工具
  2. .NET并行计算和并发3.2-多线程调用Invoke
  3. JPA问题汇总
  4. 多线程callable使用方法
  5. C程序第三次作业
  6. Git删除分支/恢复分支
  7. c语言笔记4数据的输入和输出
  8. leetcode 3.Longest Substring Without Repeating Charcters
  9. Python开发 基礎知識 3.類別&方法 (bool & str) (未完待續)
  10. 对数据进行GZIP压缩或解压缩