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 Solution 1:
Time: O(N^2)
Space: O(Height)
 # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None class Solution:
def pathSum(self, root: TreeNode, sum: int) -> int:
if root is None:
return 0
cur = self.helper(root, sum)
left = self.pathSum(root.left, sum)
right = self.pathSum(root.right, sum)
return cur + left + right def helper(self, root, sum):
if root is None:
return 0
left = self.helper(root.left, sum - root.val)
right = self.helper(root.right, sum - root.val)
if sum == root.val:
return 1 + left + right
return left + right
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
int count = 0;
public int pathSum(TreeNode root, int sum) {
List<Integer> list = new ArrayList<>();
helper(root, list, sum);
return count;
} private void helper(TreeNode root, List<Integer> list, int sum) {
if (root == null) {
return;
}
list.add(root.val);
int num = 0;
for (int i = list.size() - 1; i >= 0; i--) {
num += list.get(i);
if (num == sum) {
count += 1;
}
}
helper(root.left, list, sum);
helper(root.right, list, sum);
list.remove(list.size() - 1);
}
}

Solution 2:

Time: O(N)

Space: O(N)

 # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None class Solution:
def pathSum(self, root: TreeNode, sum: int) -> int:
if root is None:
return 0
self.res = 0
# initilized with 0 as prefix instead of empty b/c need to conver path coming from root
my_dict = {0 : 1}
self.helper(root, sum, 0, my_dict)
return self.res def helper(self, root, sum, cur_sum, my_dict):
if root is None:
return
cur_sum += root.val
reminder = cur_sum - sum
# use reminder as key
if reminder in my_dict:
self.res += my_dict[reminder]
my_dict[cur_sum] = my_dict.get(cur_sum, 0) + 1
# pass cur_sum to children
left = self.helper(root.left, sum, cur_sum, my_dict)
right = self.helper(root.right, sum, cur_sum, my_dict)
my_dict[cur_sum] -= 1
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
int count = 0;
public int pathSum(TreeNode root, int sum) {
Map<Integer, Integer> map = new HashMap<>();
// check path from root
map.put(0, 1);
helper(root, 0, sum, map);
return count;
} private void helper(TreeNode root, int curSum, int sum, Map<Integer, Integer> map) {
if (root == null) {
return;
}
int tmpSum = curSum + root.val;
if (map.containsKey(tmpSum - sum)) {
count += map.get(tmpSum - sum);
}
map.put(tmpSum, map.getOrDefault(tmpSum, 0) + 1);
helper(root.left, tmpSum, sum, map);
helper(root.right, tmpSum, sum, map);
map.put(tmpSum, map.get(tmpSum) - 1);
}
}

[LC] 437. Path Sum III的更多相关文章

  1. 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 ...

  2. 【leetcode】437. Path Sum III

    problem 437. Path Sum III 参考 1. Leetcode_437. Path Sum III; 完

  3. leetcode 112. Path Sum 、 113. Path Sum II 、437. Path Sum III

    112. Path Sum 自己的一个错误写法: class Solution { public: bool hasPathSum(TreeNode* root, int sum) { if(root ...

  4. 437. Path Sum III

    原题: 437. Path Sum III 解题: 思路1就是:以根节点开始遍历找到适合路径,以根节点的左孩子节点开始遍历,然后以根节点的右孩子节点开始遍历,不断循环,也就是以每个节点为起始遍历点 代 ...

  5. 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 ...

  6. [LeetCode] 437. Path Sum III 路径和 III

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

  7. leetcode 437 Path Sum III 路径和

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

  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. 【easy】437. Path Sum III 二叉树任意起始区间和

    /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode ...

随机推荐

  1. DevOps专题 |监控,可观测性与数据存储

    对于DevOps而言,监控是其中重要的一环,上一次的专题内容中,我们与大家分享了大型企业级监控系统的设计.今天我们将和大家从另一个角度进一步探讨互联网工程技术领域的监控设计(monitoring):系 ...

  2. c++静态库和动态库的添加

    # 声明要求的 cmake 最低版本cmake_minimum_required(VERSION 2.8)# 声明一个 cmake 工程project(helloSLAM) # 设置编译模式set( ...

  3. Java 面向对象 异常处理:RunTimeexception,try-catch,异常声明throws,自定义异常,throw和throws的区别,多异常处理(9)

    Java 面向对象 异常处理:RunTimeexception,try-catch,异常声明throws,自定义异常,throw和throws的区别,多异常处理(9)

  4. uni-app: 如何实现增量更新功能?

    都知道,很多APP都有增量更新功能,Uni APP也是在今年初,推出了增量更新功能,今天我们就来学习一波. 当然,很多应用市场为了防止开发者不经市场审核许可,给用户提供违法内容,对增量更新大多持排斥态 ...

  5. 17.3.12---sys模块

    1---sys是system的缩写,用来获取操作系统和编译器的一些配置,设置和操作,如判断文件和文件夹是否存在,创建文件夹,获取系统版本之类的操作 import sys  #导入sys模块 2--一些 ...

  6. Python语言学习:字典常用的方法

    1. 增加:字典[key]=value(不存在的key和value) info={ 'stu1101':'TengLan', 'stu1102':'LuoZe', 'stu1103':'XiaoZe' ...

  7. 如何正确理解SQL关联子查询

    一.基本逻辑 对于外部查询返回的每一行数据,内部查询都要执行一次.在关联子查询中是信息流是双向的.外部查询的每行数据传递一个值给子查询,然后子查询为每一行数据执行一次并返回它的记录.然后,外部查询根据 ...

  8. Methyl-SeqDNA的甲基化图谱|DNase I-Seq|ChIP-Seq|3C-Seq|

    生物医学大数据 Methyl-SeqDNA的甲基化图谱 DNase I-Seq全基因组染色质DNA的开放程度.非基因编码区的调控元件的分布 DNase I高敏感位点:基因处于转录活性状态时,其染色质结 ...

  9. Java进行http请求时,放置会话信息到header里面

    public class CreateHttpTest { public static void main(String[] args) { createHttp(); } public static ...

  10. 第一行代码近期bug及解决

    Android学习笔记(5)----启动 Theme.Dialog 主题的Activity时程序崩溃的解决办法https://www.cnblogs.com/dongling/p/6476308.ht ...