[LC] 437. Path Sum III
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的更多相关文章
- 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 ...
- 【leetcode】437. Path Sum III
problem 437. Path Sum III 参考 1. Leetcode_437. Path Sum III; 完
- 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 ...
- 437. Path Sum III
原题: 437. Path Sum III 解题: 思路1就是:以根节点开始遍历找到适合路径,以根节点的左孩子节点开始遍历,然后以根节点的右孩子节点开始遍历,不断循环,也就是以每个节点为起始遍历点 代 ...
- 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 ...
- [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 ...
- leetcode 437 Path Sum III 路径和
相关问题:112 path sum /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNo ...
- 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 ...
- 【easy】437. Path Sum III 二叉树任意起始区间和
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode ...
随机推荐
- C语言笔记 15_标准库&locale&math&setjmp&signal&stdarg&stddef
<locale.h> 简介 locale.h 头文件定义了特定地域的设置,比如日期格式和货币符号.接下来我们将介绍一些宏,以及一个重要的结构 struct lconv 和两个重要的函数. ...
- 安卓和iOS统一下载页面
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...
- JAVA多线程之状态转换图
线程状态转换图如下: 1.新建(new):线程对象被创建后就进入了新建状态.如:Thread thread = new Thread(); 2.就绪状态(Runnable):也被称为“可执行状态”.线 ...
- ZJNU 2208 - 你渴望力量吗
在图的最外面套一层0(防止到头) 然后搜索图有多少块在 '0'有两块0,一块1 '1'有一块0,一块1 其余情况不存在 #include<stdio.h> ],dx[]={,,,-},dy ...
- ZJNU 1542 - 三角形(续)--中高级
从小到大排序后 先固定一遍,另外两边递增查找 即固定 i,j=i+1,k=j+1 然后让k递增到 a[i]+a[j]<=a[k] 时 此时不能凑成一个三角形 答案增加 k-1-j 组 此时不需要 ...
- DispatcherServlet和ContextLoaderListener,还有spring+servlet3.0 无web.xml启动问题
上篇提到: 关于spring +springmvc中两个spring应用上下文(DispatcherServlet和ContextLoaderListener)的问题,挺让人迷糊的. 他们都是加载Be ...
- 杨辉三角(C语言)
杨辉三角 杨辉三角,是二项式系数在三角形中的一种几何排列,中国南宋数学家杨辉1261年所著的<详解九章算法>一书中出现.在欧洲,帕斯卡(1623----1662)在1654年发现这一规律, ...
- Linux inode 理解
inode 硬盘的最小存储单位叫做"扇区"(Sector).每个扇区储存512字节(相当于0.5KB).操作系统读取硬盘的时候,不会一个个扇区地读取,这样效率太低,而是一次性读取一 ...
- vim中的正则表达式替换
这个总结的不错 http://tanqisen.github.io/blog/2013/01/13/vim-search-replace-regex/
- java基本类型和包装类型
int 是基本类型,直接存数值 Integer是类,产生对象时用一个引用指向这个对象 Java把内存划分成两种:一种是栈内存,另一种是堆内存 在函数中定义的一些基本类型的变量和对象的引用变 ...