LeetCode算法题-Path Sum III(Java实现)
这是悦乐书的第227次更新
01 看题和准备
今天介绍的是LeetCode算法题中Easy级别的第94题(顺位题号是437)。您将获得一个二叉树,其中每个节点都包含一个整数值。找到与给定值相加的路径数。路径不需要在根或叶子处开始或结束,但必须向下(仅从父节点行进到子节点)。树的节点数不超过1,000个,值范围为-1,000,000到1,000,000。例如:
root = [10,5,-3,3,2,null,11,3,-2,null,1],sum = 8
10
/ \
5 -3
/ \ \
3 2 11
/ \ \
3 -2 1
返回3。总和为8的路径为:
1、5 - > 3
2、5 - > 2 - > 1
3、-3 - > 11
本次解题使用的开发工具是eclipse,jdk使用的版本是1.8,环境是win7 64位系统,使用Java语言编写和测试。
02 第一种解法
使用深度优先算法(DFS),因为题目说可以在任意节点开始,可以在任意节点结束,因此在开始位置有两个选择:从根节点开始;从根节点的子节点开始。而从根节点的子节点开始,此子问题和问题本身性质一样,需要调用自身。而从根节点开始,则需要调用另外一个方法,此方法同样是两个参数,当前节点和sum。
定义一个记数变量,记录可能的路径数。如果当前节点为null,返回0。如果当前节点值和sum相等,记数加1,同时对于当前节点的左节点、右节点继续调用此方法,而第二个参数sum,则需要减掉当前节点的值。
public int pathSum(TreeNode root, int sum) {
if (root == null) {
return 0;
}
return findPath(root, sum) + pathSum(root.left, sum) + pathSum(root.right, sum);
}
public int findPath(TreeNode root, int sum) {
int result = 0;
if (root == null) {
return result;
}
if (sum == root.val) {
result++;
}
result += findPath(root.left, sum-root.val);
result += findPath(root.right, sum-root.val);
return result;
}
03 第二种解法
此解法来自讨论区。对于树中的每个父节点,我们有两个选择:
1.将它包括在达到总和的路径中。
2.不要将其包含在达到总和的路径中。
对于树中的每个子节点,我们有2个选择:
1.取走父节点留给你的东西。
2.从自己开始形成路径。
int target;
Set<TreeNode> visited;
public int pathSum2(TreeNode root, int sum) {
target = sum;
//to store the nodes that have already tried to start path by themselves.
visited = new HashSet<TreeNode>();
return pathSumHelper(root, sum, false);
}
public int pathSumHelper(TreeNode root, int sum, boolean hasParent) {
if(root == null) return 0;
//the hasParent flag is used to handle the case when parent path sum is 0.
//in this case we still want to explore the current node.
if (sum == target && visited.contains(root) && !hasParent) {
return 0;
}
if (sum == target && !hasParent) {
visited.add(root);
}
int count = (root.val == sum) ? 1 : 0;
count += pathSumHelper(root.left, sum - root.val, true);
count += pathSumHelper(root.right, sum - root.val, true);
count += pathSumHelper(root.left, target , false);
count += pathSumHelper(root.right, target, false);
return count;
}
04 第三种解法
此解法同样来自讨论区,使用HashMap来操作。
传送门:https://leetcode.com/problems/path-sum-iii/discuss/91878/17-ms-O(n)-java-Prefix-sum-method
public int pathSum3(TreeNode root, int sum) {
Map<Integer, Integer> map = new HashMap<>();
//Default sum = 0 has one count
map.put(0, 1);
return backtrack(root, 0, sum, map);
}
public int backtrack(TreeNode root, int sum, int target, Map<Integer, Integer> map){
if (root == null) {
return 0;
}
sum += root.val;
//See if there is a subarray sum equals to target
int res = map.getOrDefault(sum - target, 0);
map.put(sum, map.getOrDefault(sum, 0)+1);
//Extend to left and right child
res += backtrack(root.left, sum, target, map);
res += backtrack(root.right, sum, target, map);
//Remove the current node so it won't affect other path
map.put(sum, map.get(sum)-1);
return res;
}
05 小结
算法专题目前已连续日更超过两个月,算法题文章94+篇,公众号对话框回复【数据结构与算法】、【算法】、【数据结构】中的任一关键词,获取系列文章合集。
以上就是全部内容,如果大家有什么好的解法思路、建议或者其他问题,可以下方留言交流,点赞、留言、转发就是对我最大的回报和支持!
LeetCode算法题-Path Sum III(Java实现)的更多相关文章
- LeetCode算法题-Path Sum(Java实现)
这是悦乐书的第169次更新,第171篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第28题(顺位题号是112).给定二叉树和整数sum,确定树是否具有根到叶路径,使得沿路 ...
- LeetCode算法题-Two Sum IV - Input is a BST(Java实现)
这是悦乐书的第280次更新,第296篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第148题(顺位题号是653).给定二进制搜索树和目标数,如果BST中存在两个元素,使得 ...
- LeetCode算法题-Range Sum Query Immutable(Java实现)
这是悦乐书的第204次更新,第214篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第70题(顺位题号是303).给定整数数组nums,找到索引i和j(i≤j)之间的元素之 ...
- LeetCode算法题-Image Smoother(Java实现)
这是悦乐书的第282次更新,第299篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第150题(顺位题号是661).给定表示图像灰度的2D整数矩阵M,您需要设计一个平滑器以 ...
- LeetCode算法题-Employee Importance(Java实现)
这是悦乐书的第291次更新,第309篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第159题(顺位题号是690).定义员工信息的数据结构,其中包括员工的唯一ID,他的重要 ...
- LeetCode算法题-Baseball Game(Java实现)
这是悦乐书的第288次更新,第305篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第156题(顺位题号是682).你现在是棒球比赛点记录器.给定一个字符串列表,每个字符串 ...
- LeetCode算法题-Set Mismatch(Java实现)
这是悦乐书的第279次更新,第295篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第147题(顺位题号是645).集合S最初包含从1到n的数字. 但不幸的是,由于数据错误 ...
- LeetCode算法题-Perfect Number(Java实现)
这是悦乐书的第249次更新,第262篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第116题(顺位题号是507).我们定义Perfect Number是一个正整数,它等于 ...
- LeetCode算法题-String Compression(Java实现)
这是悦乐书的第230次更新,第242篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第97题(顺位题号是443).给定一组字符,就地压缩它.压缩后的长度必须始终小于或等于原 ...
随机推荐
- Go基础系列:为select设置超时时间
Go channel系列: channel入门 为select设置超时时间 nil channel用法示例 双层channel用法示例 指定goroutine的执行顺序 After() 谁也无法保证某 ...
- [转]How to Add Bootstrap to an Angular CLI project
本文转自:https://loiane.com/2017/08/how-to-add-bootstrap-to-an-angular-cli-project/ In this article we w ...
- 在Windows 10中使用内置的SSH Client连接远程的Linux虚拟机
无意中发现这个功能.一直以来,在Windows平台上面要通过SSH连接Linux都需要借助第三方工具,而且往往还不是很方便.但其实在去年12月份的更新中,已经包含了一个beta版本的SSH Clien ...
- sqlserver 操作数据表语句模板
从网上搜的,一点一点加吧. -----------设置事务全部回滚----------------- SET XACT_ABORT ON BEGIN BEGIN TRY BEGIN TRANSACTI ...
- 【C#】list 去重(转载)
Enumerable.Distinct 方法 是常用的LINQ扩展方法,属于System.Linq的Enumerable方法,可用于去除数组.集合中的重复元素,还可以自定义去重的规则. 有两个重载方法 ...
- Netty实战三之Netty的组件和设计
有关Netty,我们可以从两个视角来讨论Netty:类库的视角以及框架的视角,对于使用Netty编写高效的.可重用的和可维护的代码来说,两者缺一不可. Netty解决了两个响应的关注领域,可以大致标志 ...
- Codeforces Round #304 (Div. 2) -----CF546
A. Soldier and Bananas A soldier wants to buy w bananas in the shop. He has to pay k dollars for t ...
- node实现简单的群体聊天工具
一.使用的node模块 1.express当做服务器 2.socket.io 前后通信的桥梁 3.opn默认打开浏览器的模块(本质上用不到) 难点:前后通信 源码地址:https://github.c ...
- 05-HTML-超链接标签
<html> <head> <title>超链接标签学习</title> <meta charset="utf-8"/&g ...
- Markdown简单上手
标题 # +内容 一级标题 二级标题 三级标题 四级标题 五级标题 六级标题 字体 1. 加粗(Ctrl+B) **加粗** 2. 斜体(Ctrl+I) *斜体* 3. 斜体加粗(Ctrl+B+I) ...