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:

  1. root = [10,5,-3,3,2,null,11,3,-2,null,1], sum = 8
  2.  
  3. 10
  4. / \
  5. 5 -3
  6. / \ \
  7. 3 2 11
  8. / \ \
  9. 3 -2 1
  10.  
  11. Return 3. The paths that sum to 8 are:
  12.  
  13. 1. 5 -> 3
  14. 2. 5 -> 2 -> 1
  15. 3. -3 -> 11

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

解法:递归。

Python:

  1. class Solution(object):
  2. def pathSum(self, root, sum):
  3. """
  4. :type root: TreeNode
  5. :type sum: int
  6. :rtype: int
  7. """
  8. def pathSumHelper(root, curr, sum, lookup):
  9. if root is None:
  10. return 0
  11. curr += root.val
  12. result = lookup[curr-sum] if curr-sum in lookup else 0
  13. lookup[curr] += 1
  14. result += pathSumHelper(root.left, curr, sum, lookup) + \
  15. pathSumHelper(root.right, curr, sum, lookup)
  16. lookup[curr] -= 1
  17. if lookup[curr] == 0:
  18. del lookup[curr]
  19. return result
  20.  
  21. lookup = collections.defaultdict(int)
  22. lookup[0] = 1
  23. return pathSumHelper(root, 0, sum, lookup)

Python:

  1. class Solution2(object):
  2. def pathSum(self, root, sum):
  3.  
  4. def pathSumHelper(root, prev, sum):
  5. if root is None:
  6. return 0
  7.  
  8. curr = prev + root.val;
  9. return int(curr == sum) + \
  10. pathSumHelper(root.left, curr, sum) + \
  11. pathSumHelper(root.right, curr, sum)
  12.  
  13. if root is None:
  14. return 0
  15.  
  16. return pathSumHelper(root, 0, sum) + \
  17. self.pathSum(root.left, sum) + \
  18. self.pathSum(root.right, sum)

C++:

  1. class Solution {
  2. public:
  3. int pathSum(TreeNode* root, int sum) {
  4. unordered_map<int, int> m;
  5. m[0] = 1;
  6. return helper(root, sum, 0, m);
  7. }
  8. int helper(TreeNode* node, int sum, int curSum, unordered_map<int, int>& m) {
  9. if (!node) return 0;
  10. curSum += node->val;
  11. int res = m[curSum - sum];
  12. ++m[curSum];
  13. res += helper(node->left, sum, curSum, m) + helper(node->right, sum, curSum, m);
  14. --m[curSum];
  15. return res;
  16. }
  17. };  

C++:

  1. class Solution {
  2. public:
  3. int pathSum(TreeNode* root, int sum) {
  4. if (!root) return 0;
  5. return sumUp(root, 0, sum) + pathSum(root->left, sum) + pathSum(root->right, sum);
  6. }
  7. int sumUp(TreeNode* node, int pre, int& sum) {
  8. if (!node) return 0;
  9. int cur = pre + node->val;
  10. return (cur == sum) + sumUp(node->left, cur, sum) + sumUp(node->right, cur, sum);
  11. }
  12. };

  

  

  

类似题目:

[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. 一加5安卓P刷入twrp的recovery

    本文介绍的方法属于普适性的一般方法,比网上的各种工具箱会繁琐.但是工具箱不一定一直会更新(之前一加论坛的刷机工具箱已经停止更新了,估计是作者不用一加5了吧,毕竟已经好几年的手机了).并且如果你手机更新 ...

  2. el-table 多列显示隐藏造成内容错乱

  3. SQL异常总结

    1.resultType和resultMap写错时,启动时就会报错 原因: 2.The error occurred while handling results ### SQL: select US ...

  4. Echo团队Alpha冲刺 - 测试随笔

    目录 测试工作的安排 测试工具选择和运用 测试用例文档 测试体会 项目测试评述 测试工作的安排 模块 测试人 测试内容 单元测试 李东权,黄少勇 测试类或者函数是否能正确处理用户请求 接口测试 林弘杰 ...

  5. c#——ref 和 out 的区别

    一个用关键字 ref 标示,一个用 out 标示. 牵扯到数据是引用类型还是值类型. 一般用这两个关键字你是想调用一个函数将某个值类型的数据通过一个函数后进行更改.传 out 定义的参数进去的时候这个 ...

  6. js遍历localStorage的键值对

    //遍历本地存储localStorage for (var i = 0; i < localStorage.length; i++) { var key = localStorage.key(i ...

  7. 多项式的各类计算(多项式的逆/开根/对数/exp/带余除法/多点求值)

    预备知识:FFT/NTT 多项式的逆 给定一个多项式 F(x)F(x)F(x),请求出一个多项式 G(x)G(x)G(x),满足 F(x)∗G(x)≡1(mod xn)F(x)*G(x) \equiv ...

  8. 实现redis缓存,缓存穿透简单原理

    String get(String key) { String value = redis.get(key); if (value == null) { if (redis.setnx(key_mut ...

  9. rhcsa备战笔记

    笔记全部手打 转载请加原文链接 0)重置密码开机按e 找到linux16行 rd.break console=tty0  ctrl+xmount -o remount,rw /sysrootchroo ...

  10. c++处理字符串string.find()与string::npos

    1. string s  = “xxx”; int a = s.find(‘x’); 如果没有匹配到,那么a = string::npos;