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

给定一个二叉树,求从某一节点开始的路径的和等于给定值,不必从根节点开始,可从二叉树的任意一个节点开始,节点值有正有负。

解法:递归。

Python:

class Solution(object):
def pathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: int
"""
def pathSumHelper(root, curr, sum, lookup):
if root is None:
return 0
curr += root.val
result = lookup[curr-sum] if curr-sum in lookup else 0
lookup[curr] += 1
result += pathSumHelper(root.left, curr, sum, lookup) + \
pathSumHelper(root.right, curr, sum, lookup)
lookup[curr] -= 1
if lookup[curr] == 0:
del lookup[curr]
return result lookup = collections.defaultdict(int)
lookup[0] = 1
return pathSumHelper(root, 0, sum, lookup)

Python:

class Solution2(object):
def pathSum(self, root, sum): def pathSumHelper(root, prev, sum):
if root is None:
return 0 curr = prev + root.val;
return int(curr == sum) + \
pathSumHelper(root.left, curr, sum) + \
pathSumHelper(root.right, curr, sum) if root is None:
return 0 return pathSumHelper(root, 0, sum) + \
self.pathSum(root.left, sum) + \
self.pathSum(root.right, sum)

C++:

class Solution {
public:
int pathSum(TreeNode* root, int sum) {
unordered_map<int, int> m;
m[0] = 1;
return helper(root, sum, 0, m);
}
int helper(TreeNode* node, int sum, int curSum, unordered_map<int, int>& m) {
if (!node) return 0;
curSum += node->val;
int res = m[curSum - sum];
++m[curSum];
res += helper(node->left, sum, curSum, m) + helper(node->right, sum, curSum, m);
--m[curSum];
return res;
}
};  

C++:

class Solution {
public:
int pathSum(TreeNode* root, int sum) {
if (!root) return 0;
return sumUp(root, 0, sum) + pathSum(root->left, sum) + pathSum(root->right, sum);
}
int sumUp(TreeNode* node, int pre, int& sum) {
if (!node) return 0;
int cur = pre + node->val;
return (cur == sum) + sumUp(node->left, cur, sum) + sumUp(node->right, cur, sum);
}
};

  

  

  

类似题目:

[LeetCode] 112. Path Sum 路径和

[LeetCode] 113. Path Sum II 路径和 II

All LeetCode Questions List 题目汇总

[LeetCode] 437. Path Sum III 路径和 III的更多相关文章

  1. [LeetCode] 113. Path Sum II 路径和 II

    Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given su ...

  2. 47. leetcode 437. Path Sum III

    437. Path Sum III You are given a binary tree in which each node contains an integer value. Find the ...

  3. [LeetCode] 437. Path Sum III_ Easy tag: DFS

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

  4. LeetCode 437. Path Sum III (路径之和之三)

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

  5. leetcode 437 Path Sum III 路径和

      相关问题:112 path sum /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNo ...

  6. LeetCode 113. Path Sum II路径总和 II (C++)

    题目: Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the give ...

  7. leetcode 113. Path Sum II (路径和) 解题思路和方法

    Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given su ...

  8. Leetcode 437. Path Sum III

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

  9. LeetCode 437. Path Sum III (STL map前缀和)

    找遍所有路径,特判以根为起点的串即可. 代码: /** * Definition for a binary tree node. * struct TreeNode { * int val; * Tr ...

随机推荐

  1. linux下安装cryptography兼论查找合适pip的whl文件技巧

    cryptography这个包,如果源码安装,需要GCC之类的编译,在生产环境不太现实. 所以选择了whl文件安装. 但在官方提供的whl文件里,没有我们熟悉的cp36-cp36m这样的命名文件,肿么 ...

  2. 微信小程序~页面跳转和路由

    一个小程序拥有多个页面,我们可以通过wx.navigateTo推入一个新的页面,如图3-6所示,在首页使用2次wx.navigateTo后,页面层级会有三层,我们把这样的一个页面层级称为页面栈.

  3. 51nod 2500 后面第一个大于

    小b有一个长度为n的序列t,现在她对于每个i,求最小的正数j满足i+j≤ni+j≤n且ti+j>titi+j>ti,输出j,如果不存在这样的j,则输出0. 样例解释: 对于i=1,t2&g ...

  4. linux中如何升级Python

    一.使用wget 下载Python 安装包 我是在虚拟中当中安装的: wget http://www.python.org/ftp/python/3.7.0/Python-3.7.0.tgz 报错: ...

  5. spring jar包的作用

    spring.jar是包含有完整发布的单个jar 包,spring.jar中包含除了spring-mock.jar里所包含的内容外其它所有jar包的内容,因为只有在开发环境下才会用到 spring-m ...

  6. janusgraph-mgmt中的一些操作

    关闭事务 mgmt = graph.openManagement(); ids = mgmt.getOpenInstances(); for(String id : ids){if(!id.conta ...

  7. Spark Partition

    分区的意义 Spark RDD 是一种分布式的数据集,由于数据量很大,因此它被切分成不同分区并存储在各个Worker节点的内存中.从而当我们对RDD进行操作时,实际上是对每个分区中的数据并行操作.Sp ...

  8. P2388 阶乘之乘

    首先感谢wxy学长之前告诉我这道题,结果今天竟然一眼切了,咕咕咕 题目链接: P2388 阶乘之乘 题目思路: 第一眼看到一定想到的是先求一下阶乘然后看最后又几个零,但是这样会TIL啊 想一下0是怎么 ...

  9. vue-element-admin 实现动态路由(从后台查询出菜单列表绑定)

    1. 在路由实例中保留基础路由 router/index.js中只需要保留基础路由,其他的都删了 2. 获取用户菜单,并保存到Vuex中 stroe/modules/user.js中,有个getInf ...

  10. Koa 脚手架创建项目

    Koa 脚手架创建项目 通过应用 koa 脚手架生成工具 可以快速创建一个基于 koa2 的应用的骨架 全局安装koa npm install koa-generator -g //必须安装到全局 创 ...