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. Java 接口理解

    学习Spring有一段时间了,对java也有了一点了解,最不能理解的就是接口, 即使是写了接口并实现了它,依然无法理解它到底有什么用?看了其他几篇博客,总结了一下自己的理解. 在JAVA编程语言中是一 ...

  2. js获取指定日期n天之后的日期

    function addDays(date, days,seperator='-') { let oDate = new Date(date).valueOf(); let nDate = oDate ...

  3. tomcat8.5的安装、卸载、配置和部署

    安装和卸载 下载 http://tomcat.apache.org/ 环境变量 1.点击此电脑 右键—>属性. 2.创建变量名为CATALINA_HOME,的值为所解压安装tomcat的本地目录 ...

  4. 201771010123汪慧和《面向对象程序设计JAVA》第九周实验总结

    一.理论部分 1.异常 (1)异常处理的任务就是将控制权从错误产生的地方转移给能够处理这种情况的错误处理器. (2)程序中可能出现的错误和问题:a.用户输入错误.b.设备错误.c.物理限制.d.代码错 ...

  5. Python 重新加载模块

    每个Python文件中的import modulename只被加载一遍,如果在运行过程中,这个Module被更改了,即使在在interpretor中运行import 语句也没用. 可以使用import ...

  6. 面试准备 DOM

    基本概念:Dom事件的级别 Dom0 级别 element.onclick=function() {} Dom1  没有制定事件相关的 Dom2 element.addEventListener(&q ...

  7. Java--类初始化

    package httpclient.demo; public class StaticTest { public static void main(String[] args) { staticFu ...

  8. JAVA 算法练习(一)

    用java写了几道编程题目,分享给大家 语法和C语言几乎一样,不懂 java 会 c 也可以看明白的. 最大连续数列和 题目说明 对于一个有正有负的整数数组,请找出总和最大的连续数列.给定一个int数 ...

  9. PHP时间戳常用转换

    //设置中国时区 date_default_timezone_set('PRC'); //今天的时间搓 $today_start = strtotime(date('Y-m-d',time()).' ...

  10. h3c 瘦ap无法上线解决办法(WA4320i-ACN)

    瘦ap无法上线的原因主要有两个:1.无法获取IP地址 2 .版本 胖ap转瘦ap: 1.使用网线+web对ap进行管理,默认IP地址为:192.168.0.50,用户名:admin 密码:h3capa ...