/**
* 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] -=

leetcode437的更多相关文章

  1. [Swift]LeetCode437. 路径总和 III | Path Sum III

    You are given a binary tree in which each node contains an integer value. Find the number of paths t ...

  2. 第34-3题:LeetCode437. Path Sum III

    题目 二叉树不超过1000个节点,且节点数值范围是 [-1000000,1000000] 的整数. 示例: root = [10,5,-3,3,2,null,11,3,-2,null,1], sum ...

  3. LeetCode通关:连刷三十九道二叉树,刷疯了!

    分门别类刷算法,坚持,进步! 刷题路线参考:https://github.com/youngyangyang04/leetcode-master 大家好,我是拿输出博客来督促自己刷题的老三,这一节我们 ...

随机推荐

  1. mysql错误集合

    一.This function has none of DETERMINISTIC, NO SQL, or READS SQL DATA in its de 错误解决办法 这是我们开启了bin-log ...

  2. python day20面向对象-属性,类方法,静态方法

    一.属性的初识 # class Person: # # def __init__(self,name,hight,weight): # self.name = name # self.__hight ...

  3. Scrapy、Scrapy-redis组件

    目录 Scrapy 一.安装 二.基本使用 1. 基本命令 2.项目结构以及爬虫应用简介 3. 小试牛刀 4. 选择器 5. 格式化处理 6.中间件 7. 自定制命令 8. 自定义扩展 9. 避免重复 ...

  4. Gym - 100783G:Playing With Geometry (几何 离散化 )

    pro:给定规则的多边形,规则是指顶点都在整点上,而且是相互垂直的边的交点. 现在给定两个多边形A,B,问A,B缩小,旋转后是否可以变为同一个图形. sol:缩小的话,直接离散化即可,就可以去掉没用的 ...

  5. 01bootstrap_基本结构和布局

    01bootstrap_基本结构 学习bootstrap需要下载必要的文件:www.bootcss.com 基本结构 container page-header 布局 1.响应式布局:containe ...

  6. Deploy Descriptor

    之前我们在编写HelloWorld项目时,在WEB-INF目录下创建了一个web.xml文件.这个文件叫做部署描述文件,每个Servlet应用程序的部署描述文件的名称都是web.xml.Web容器在启 ...

  7. PythonStudy——阶段总结

    每个数据类型的最大特点是什么? (1)int整型:用于存放整形对象,是不可变类型.若将一个整数赋值给一个变量名,python可自动将其设置为int型. 例如:age = 30 这里的age对象的typ ...

  8. PythonStudy——逻辑运算符 Logical Operators

    在Python中,None.任何数值类型中的0.空字符串“”.空元组().空列表[].空字典{}都被当作False,还有自定义类型,如果实现了 __ nonzero __ () 或 __ len __ ...

  9. The Twelve-Factor Container

    转自:https://medium.com/notbinary/the-twelve-factor-container-8d1edc2a49d4?%24identity_id=550978996201 ...

  10. ILBC 运行时 (ILBC Runtime) 架构

    本文是 VMBC / D# 项目 的 系列文章, 有关 VMBC / D# , 见 <我发起并创立了一个 VMBC 的 子项目 D#>(以下简称 <D#>)  https:// ...