当前位置:网站首页>【二叉树】路径总和II
【二叉树】路径总和II
2022-08-01 13:56:00 【不写博客就不爽】
路径总和II
这道题目10分钟就可以完成了,最近在练习中有收获啊,加油

路径总和,分成左右两个子树进行,要注意的是Java这里需要把路径进行额外保存,否则直接存path都是null
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */
class Solution {
private List<List<Integer>> ret = new ArrayList<>();
public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
if(root == null) return ret;
List<Integer> path = new ArrayList<>();
searchPath(root, targetSum, path);
return ret;
}
private void searchPath(TreeNode root, int targetSum, List<Integer> path){
if(root == null) return;
if(root.left == null && root.right == null){
if(root.val == targetSum){
List<Integer> ans = new ArrayList<>();
for(int i = 0; i < path.size(); i++){
ans.add(path.get(i));
}
ans.add(root.val);
ret.add(ans);
}
}
path.add(root.val);
searchPath(root.left, targetSum-root.val, path);
searchPath(root.right, targetSum-root.val, path);
path.remove(path.size()-1);
}
}
边栏推荐
- leetcode: 1201. Ugly Number III [Dichotomy + Mathematics + Inclusion and Exclusion Principle]
- opencv 保存图片imwrite
- Istio Pilot代码深度解析
- Qt实战案例(55)——利用QDir删除选定文件目录下的空文件夹
- 超全!全国近90所大学考研报录比汇总!
- E - Red and Blue Graph (Combinatorics)
- A Beginner's Guide to Performance Testing
- AD单片机九齐单片机NY8B062D SOP16九齐
- 50W+小程序开发者背后的数据库降本增效实践
- E - Red and Blue Graph(组合数学)
猜你喜欢

论文详读《基于改进 LeNet-5 模型的手写体中文识别》,未完待补充

NebulaGraph v3.2.0 性能报告

全链路灰度在数据库上我们是怎么做的?

【StoneDB Class】Introduction Lesson 2: Analysis of the Overall Architecture of StoneDB

免费使用高性能的GPU和TPU—谷歌Colab使用教程

gpio模拟串口通信

台积电认清了形势,新的建厂计划没有美国,中国芯片也得到重视

207.数组序号转换

微信UI在线聊天源码 聊天系统PHP采用 PHP 编写的聊天软件,简直就是一个完整的迷你版微信

NebulaGraph v3.2.0 Performance Report
随机推荐
数字孪生北京故宫,元宇宙推进旅游业进程
sql is not null 优化(oracle语句索引优化)
响应式2022英文企业官网源码,感觉挺有创意的
PAT 1163 Dijkstra Sequence(30)
十九届浙大城院程序设计竞赛 F.Sum of Numerators(数学/找规律)
How do we do full-link grayscale on the database?
快速理解拉格朗日乘子法
NebulaGraph v3.2.0 Performance Report
树和二叉树的转换
E - Red and Blue Graph(组合数学)
PyTorch 进阶之路:在 GPU 上训练深度神经网络
mysql的基本使用
【每日一题】1161. 最大层内元素和
iPhone难卖,被欧洲反垄断的服务业务也难赚钱了,苹果的日子艰难
leetcode.26 删除有序数组中的重复项(set/直接遍历)
A Beginner's Guide to Performance Testing
postgresql之page分配管理(一)
NebulaGraph v3.2.0 性能报告
8. SAP ABAP OData 服务如何支持创建(Create)操作
高仿项目协作工具【Worktile】,从零带你一步步实现组织架构、网盘、消息、项目、审批等功能