Path Sum II leetcode java
题目:
Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.
For example:
Given the below binary tree and sum = 22
,
5/ \4 8/ / \11 13 4/ \ / \7 2 5 1
return
[[5,4,11,2],[5,8,4,5] ] 题解: 这道题除了要判断是否有这样的一个path sum,还需要把所有的都可能性结果都返回,所以就用传统的DFS递归解决子问题。代码如下:
2 if(root==null)
3 return;
4 sumlist.add(root.val);
5 sum = sum-root.val;
6 if(root.left==null && root.right==null){
7 if(sum==0){
8 pathlist.add(new ArrayList<Integer>(sumlist));
9 }
10 }else{
11 if(root.left!=null)
12 pathSumHelper(root.left,sum,sumlist,pathlist);
13 if(root.right!=null)
14 pathSumHelper(root.right,sum,sumlist,pathlist);
15 }
16 sumlist.remove(sumlist.size()-1);
17 }
18
19 public List<List<Integer>> pathSum(TreeNode root, int sum) {
20 List<List<Integer>> pathlist=new ArrayList<List<Integer>>();
21 List<Integer> sumlist = new ArrayList<Integer>();
22 pathSumHelper(root,sum,sumlist,pathlist);
23 return pathlist;
24 }
Path Sum II leetcode java相关推荐
- leetcode 112. Path Sum, 113. Path Sum II | 112,113. 路径总和 I, II(Java)
题目 https://leetcode.com/problems/path-sum/ https://leetcode.com/problems/path-sum-ii/ 题解 简单的遍历二叉树,不解 ...
- [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 giv ...
- Leetcode: mimimum depth of tree, path sum, path sum II
思路: 简单搜索 总结: dfs 框架 1. 需要打印路径. 在 dfs 函数中假如 vector 变量, 不用 & 修饰的话就不需要 undo 2. 不需要打印路径, 可设置全局变量 ans ...
- LeetCode 113. Path Sum II
113. Path Sum II Given a binary tree and a sum, find all root-to-leaf paths where each path's sum eq ...
- 113. Path Sum II
/** 113. Path Sum II * 11.18 By Mingyang* 典型的backtracking,不过注意,这里的值可能是负数,所以不能用sum小于0来做任何判断* 1.长度标准:无 ...
- [Leetcode] 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: 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 ...
- LeetCode Path Sum II(dfs或者bfs)
问题:给出一个树和一个数,求出从根结点到叶子结点路径和等于这个数的所有情况 思路: 1.深度优先搜索,在到达一个深度结点时,判断是否是叶子结点,并且判断和是否等于要求的数.如果满足,说明是满足条件的一 ...
- LeetCode OJ 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 ...
最新文章
- 448. Find All Numbers Disappeared in an Array
- 无法连接到远程的SQL SERVER2000
- 51nod1347(简单逻辑)
- Java秒杀系统实战系列~RabbitMQ死信队列处理超时未支付的订单(转)
- yii学习笔记(6),数据库操作(增删改)
- 从 JDBC 到 Mybatis,看这篇就够了
- 安卓直播详细教程(一)-----bilibili开源播放器
- 第十篇:复制对象时切记复制每一个成分
- jogamp-env.xml:48: Unsupported Java version: 11. Make sure that the version of the Java compiler is
- ae saber插件_2020全套AE基础入门(下),入门首选!
- 数控机床现场数据采集与边缘计算方案
- highcharts 解决数据提示框展示的内容太多 ,部分内容无法显示的问题
- VSCode的VUE项目侧边栏打开资源管理器中的NPM脚本
- 【论文阅读笔记】faster rcnn 代码阅读细节
- 官方完整HL7 ECG-XML例子及注释翻译(1)
- 关于任天堂,你不了解的9件事
- vue中如何使用SM4国密来加密?
- vue中mapGetters函数前面的三个点是什么意思?
- 分享一个阿里云开源的流程图-g6
- java毕业设计闲一品交易平台mybatis+源码+调试部署+系统+数据库+lw