/**
* 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. effective java——31用实例域代替序数

    1,永远不要根据枚举的序数导出与它关联的值,而是要将他保存在一个实例域中.(ordinal()) public enum Ensemble { SOLO, DUET, TRIO, QUARTET, Q ...

  2. Master-Worker设计模式介绍

    Master-Worker模式是常用的并行设计模式.核心思想是,系统由两个角色组成,Master和Worker,Master负责接收和分配任务,Worker负责处理子任务.任务处理过程中,Master ...

  3. web.xml配置以及一些详解

    web.xml的根元素定义如下所示(代表当前使用哪个模版): <?xml version="1.0" encoding="UTF-8"?> < ...

  4. FCC JS基础算法题(1):Factorialize a Number(计算一个整数的阶乘)

    题目描述: 如果用字母n来代表一个整数,阶乘代表着所有小于或等于n的整数的乘积.阶乘通常简写成 n!例如: 5! = 1 * 2 * 3 * 4 * 5 = 120. 算法: function fac ...

  5. CSS样式补充第二天

    #p1{/*        border-width: 1px;*/        /*边框实线*/        /*border-style: solid;*/        /*边框虚线*/   ...

  6. UEFI+GPT双硬盘安装Win10+Ubuntu16.04双系统

    转载请注明出处:http://www.cnblogs.com/willnote/p/6725594.html 安装环境 SSD+HDD双盘,Win10安装在SSD里,HDD分出来60G安装Ubuntu ...

  7. Oracle的导入和导出

    导出命令: EXP 用户名/密码@数据库名  BUFFER=64000 file=G:\dmp\full1.dmp  OWNER=用户名 导入命令: IMP 用户名/密码@数据库名 BUFFER=64 ...

  8. 开发一个简单的postgresql extension

      主要是学习如何编写一个简单的pg extension,参考https://severalnines.com/blog/creating-new-modules-using-postgresql-c ...

  9. java_线程

    线程1    与线程相关的概念    线程与进程的区别    线程创建策略    线程组        线程创建策略        并发应用中一般有两种不同的线程创建策略        1直接控制线程 ...

  10. vue watch 可以监听子组件props里面属性的改变

    子组件watch 可以监听其props里面属性的改变 当changeFather导致calm改变时,会执行console.log('props change');