[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 ...
随机推荐
- MySQL-TPS,QPS到底是什么
计算TPS,QPS的方式 qps,tps是衡量数据库性能的关键指标,网上普遍有两种计算方式 TPS,QPS相关概念 QPS:Queries Per Second 查询量/秒,是一台服务 ...
- Okhttp 多次调用同一个方法出现错误java.net.SocketException: Socket closed
Okhttp 多次调用同一个方法出现错误java.net.SocketException: Socket closed https://blog.csdn.net/QQiqq1314/article/ ...
- Python—数据结构——链表
数据结构——链表 一.简介 链表是一种物理存储上非连续,数据元素的逻辑顺序通过链表中的指针链接次序,实现的一种线性存储结构.由一系列节点组成的元素集合.每个节点包含两部分,数据域item和指向下一个节 ...
- XCOM串口助手打印不出数据
本次实验是在基于原子的战舰开发板上的做定时器捕获实验,程序源码下载到板子上运行正常.指示灯正常显示,打开XCOM识别不来串口,原因:硬件上没有插USB转串口线: 连接上USB转串口线,软件上以显示CH ...
- python+Sqlite+Dataframe打造金融股票数据结构
5. 本地数据库 很简单的用本地Sqlite查找股票数据. DataSource类,返回的是Dataframe物件.这个Dataframe物件,在之后的业务,如计算股票指标,还需要特别处理. impo ...
- mysql查看整库个表详情
information_schema.tables字段说明 字段 含义 Table_catalog 数据表登记目录 Table_schema 数据表所属的数据库名 Table_name 表名称 Tab ...
- 绩效软件交流-ZQDJ
积分制(主管激励下属)短期任务积分 长期任务积分 制度积分 固定积分任务工作项 评估表 ,取中间值工时调整 工作表现 创新加分 难度加分 贡献加分 绩效分-积分(软件亮点) 分开做 没有管理员的中层 ...
- PAT A1133 Splitting A Linked List (25) [链表]
题目 Given a singly linked list, you are supposed to rearrange its elements so that all the negative v ...
- c#学习笔记06——XML
XML概述:eXtensible Markup Language,可扩展标记语言.网络应用开发的一项新技术.同HTML一样是一种标记语言,但是数据描述能力要强很多.XML具有描述所有已知未知数据的能力 ...
- ES6 find()
Array.prototype.find() 返回数组中满足提供测试函数的第一个元素的值,否则返回undefined let b = blogs.find(function(e) => { re ...