leetcode437
/**
* 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的更多相关文章
- [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 ...
- 第34-3题:LeetCode437. Path Sum III
题目 二叉树不超过1000个节点,且节点数值范围是 [-1000000,1000000] 的整数. 示例: root = [10,5,-3,3,2,null,11,3,-2,null,1], sum ...
- LeetCode通关:连刷三十九道二叉树,刷疯了!
分门别类刷算法,坚持,进步! 刷题路线参考:https://github.com/youngyangyang04/leetcode-master 大家好,我是拿输出博客来督促自己刷题的老三,这一节我们 ...
随机推荐
- JS中的一等公民:函数
在JavaScript中,函数可以 作为值赋给一个变量 作为参数传递给另一个函数 作为另一个函数的返回值 所以我们说JavaScript的函数是“一等公民”. 赋值: var foo = functi ...
- JavaScript 简单的实现 sleep功能 .
function start(){ // console.log("Request handle 'start' was called."); function sleep(mil ...
- Java实现数据库与eclipse的连接
JavaBean:用于传递数据,拥有与数据相关的逻辑处理 JSP:从Model接收数据并生成HTML Servlet:接收HTTP请求并控制Model和View jdbc:用于驱动连接 一.[建立数据 ...
- 获取China大陆IP段的范围
这里有几个网站提供了大陆的IP段范围.别问我要这个列表干什么,我也不知道. http://www.ip2location.com/blockvisitorsbycountry.aspx老牌网站,国内很 ...
- 深入理解使用synchronized同步方法和同步代码块的区别
一.代码块和方法之间的区别 首先需要知道代码块和方法有什么区别: 构造器和方法块,构造器可以重载也就是说明在创建对象时可以按照不同的构造器来创建,那么构造器是属于对象,而代码块呢他是给所有的对象初始化 ...
- Bootstrap如何禁止响应式布局 不适配
Bootstrap 会自动帮你针对不同的屏幕尺寸调整你的页面,使其在各个尺寸的屏幕上表现良好.下面我们列出了如何禁用这一特性,就像这个非响应式布局实例页面一样. 禁止响应式布局有如下几步: 移除 此 ...
- maven项目pom.xml第一行报错
maven项目pom.xml第一行报错 这是第一行:<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi= ...
- python2.7安装pip遇到ImportError: cannot import name HTTPSHandle
python2.7,报错如下: Traceback (most recent call last): File "/usr/local/bin/pip", line 9, in & ...
- python中datetime常用方法
# 可运算的时间方法包 >>> import datetime >>> import time >>> res = datetime.dateti ...
- java post json sample
import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; public class Te ...