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. 干货 | 基于Go SDK操作京东云对象存储OSS的入门指南

    前言 本文介绍如何使用Go语言对京东云对象存储OSS进行基本的操作,帮助客户快速通过Go SDK接入京东云对象存储,提高应用开发的效率. 在实际操作之前,我们先看一下京东云OSS的API接口支持范围和 ...

  2. WGAN将数值限制在一定范围内 Python代码 tf.clip_by_value(p, -0.01, 0.01))

    tf.clip_by_value(p, min, max))   运用的是交叉熵而不是二次代价函数. 功能:可以将一个张量中的数值限制在(min,max)内.(可以避免一些运算错误:可以保证在进行lo ...

  3. UML-领域模型的精化

    拙劣的分类和错误的概括是混乱生活的祸根.--H.G.Wells的总结 1.is-a原则 子类定义的成员变量.方法与超类必须一致.即:不能多,也不能少. 子类是“一种”超类.CreditPayment是 ...

  4. UML-基于GRASP对象设计步骤

    在OO设计建模的时候,在最后考虑系统启动时需要初始化的内容. 1.从用例开始,以下是一步步设计用例实现 处理销售 2.SSD 我们选择: makeNewSale 3.编写操作契约(复杂用例场景时) 4 ...

  5. Linux--shell 脚本免密码输入

    参考:https://www.cnblogs.com/lixigang/articles/4849527.html #!/bin/bash ssb=" password=mysql data ...

  6. PPT制作不加班的十个小窍门

    五个一键: 情景一: 上司:小万,什么字体啊这是,全部换成微软雅黑. 一键替换字体: 单击任意文本框——开始菜单栏——替换(下拉三角)——替换字体——替换为——替换.   情景二: 上司:小万,“咖啡 ...

  7. Spring Cloud Alibaba 教程 | Nacos(三)

    使用Nacos作为配置中心 前面我们已经介绍过滤Nacos是一个更易于构建云原生应用的动态服务发现.配置管理和服务管理平台.所以它可以作为注册中心和配置中心,作为注册中心Nacos可以让我们灵活配置多 ...

  8. 京东云数据库 RDS助力企业便捷运维

    iPhone6发布那年,京东在国贸等商圈送货最快速度数分钟,包括从下单到送达.这是一个极端的富含营销因素例子.即便如此,常态来看,隔天到货的这种业务模式,也是基于同样的支撑:营销业务.物流业务,大数据 ...

  9. 用IDLE调试python程序

    1. 设置断点 先放例子: import pdb a=1 b=10 pdb.set_trace()#这里是断点 c=a+b print(c) import pdb 后,用pdb.set_trace() ...

  10. 如何使用keras加载下载好的数据集

    https://blog.csdn.net/houchaoqun_xmu/article/details/78492718 [keras]解决 example 案例中 MNIST 数据集下载不了的问题 ...