[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 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
给定一个二叉树,求从某一节点开始的路径的和等于给定值,不必从根节点开始,可从二叉树的任意一个节点开始,节点值有正有负。
解法:递归。
Python:
class Solution(object):
def pathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: int
"""
def pathSumHelper(root, curr, sum, lookup):
if root is None:
return 0
curr += root.val
result = lookup[curr-sum] if curr-sum in lookup else 0
lookup[curr] += 1
result += pathSumHelper(root.left, curr, sum, lookup) + \
pathSumHelper(root.right, curr, sum, lookup)
lookup[curr] -= 1
if lookup[curr] == 0:
del lookup[curr]
return result lookup = collections.defaultdict(int)
lookup[0] = 1
return pathSumHelper(root, 0, sum, lookup)
Python:
class Solution2(object):
def pathSum(self, root, sum): def pathSumHelper(root, prev, sum):
if root is None:
return 0 curr = prev + root.val;
return int(curr == sum) + \
pathSumHelper(root.left, curr, sum) + \
pathSumHelper(root.right, curr, sum) if root is None:
return 0 return pathSumHelper(root, 0, sum) + \
self.pathSum(root.left, sum) + \
self.pathSum(root.right, sum)
C++:
class Solution {
public:
int pathSum(TreeNode* root, int sum) {
unordered_map<int, int> m;
m[0] = 1;
return helper(root, sum, 0, m);
}
int helper(TreeNode* node, int sum, int curSum, unordered_map<int, int>& m) {
if (!node) return 0;
curSum += node->val;
int res = m[curSum - sum];
++m[curSum];
res += helper(node->left, sum, curSum, m) + helper(node->right, sum, curSum, m);
--m[curSum];
return res;
}
};
C++:
class Solution {
public:
int pathSum(TreeNode* root, int sum) {
if (!root) return 0;
return sumUp(root, 0, sum) + pathSum(root->left, sum) + pathSum(root->right, sum);
}
int sumUp(TreeNode* node, int pre, int& sum) {
if (!node) return 0;
int cur = pre + node->val;
return (cur == sum) + sumUp(node->left, cur, sum) + sumUp(node->right, cur, sum);
}
};
类似题目:
[LeetCode] 113. Path Sum II 路径和 II
All LeetCode Questions List 题目汇总
[LeetCode] 437. Path Sum III 路径和 III的更多相关文章
- [LeetCode] 113. Path Sum II 路径和 II
Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given su ...
- 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_ Easy tag: DFS
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 (路径之和之三)
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 113. Path Sum II路径总和 II (C++)
题目: Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the give ...
- leetcode 113. Path Sum II (路径和) 解题思路和方法
Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given su ...
- 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 (STL map前缀和)
找遍所有路径,特判以根为起点的串即可. 代码: /** * Definition for a binary tree node. * struct TreeNode { * int val; * Tr ...
随机推荐
- anyproxy学习4-Linux(Centos)搭建anyproxy环境
前言 anyproxy可以跨平台使用,前面第一篇是搭建在windows机器上,本篇讲如何在linux上搭建anyproxy环境,当然有mac的小伙伴也可以用mac去搭建一个环境. nodejs安装 a ...
- js判断是否第一次访问跳转
今天分享一套关于Js劫持代码,进行判断第一次访问进行跳转,仅供大家参考学习! 未加密: if (c.indexOf('isfirstvisited=false') != -1) { } else { ...
- 11.vue-router编程式导航
页面导航的两种方式 声明式导航:通过点击链接实现导航的方式,叫做声明式导航 例如:普通网页中的链接或vue中的 编程式导航:通过调用JavaScrip形式的API实现导航的方式,叫做编程式导航 例如: ...
- 时间戳显示为多少分钟前,多少天前的JS处理,JS时间格式化,时间戳的转换
var dateDiff = function (timestamp) { // 补全为13位 var arrTimestamp = (timestamp + '').split(''); for ( ...
- Subarray Sum II
Description Given an positive integer array A and an interval. Return the number of subarrays whose ...
- (a2b_hex)binascii.Error: Non-hexadecimal digit found
HEX_CHAR = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'] 错误:16进制字 ...
- H5如何实现关闭当前页面,跳转到新页面?
小程序有此功能的跳转方法. 那么H5如何实现该功能? 很简单. location.replace('new.html') 这个方法可以实现 关闭当前页面,跳转到新页面 的效果. 而 windo ...
- 特征缩放(Feature Scaling)
特征缩放的几种方法: (1)最大最小值归一化(min-max normalization):将数值范围缩放到 [0, 1] 区间里 (2)均值归一化(mean normalization):将数值范围 ...
- web安全总结
一.XSS 首先说下最常见的 XSS 漏洞,XSS (Cross Site Script),跨站脚本攻击,因为缩写和 CSS (Cascading Style Sheets) 重叠,所以只能叫 XSS ...
- Java获取两个指定日期之间的所有月份
String y1 = "2016-02";// 开始时间 String y2 = "2019-12";// 结束时间 try { Date startDate ...