当前位置:网站首页>【二叉树】路径总和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]](/img/44/bf1d9b9d85939e73bc44be2f9701e1.png)
leetcode: 1201. Ugly Number III [Dichotomy + Mathematics + Inclusion and Exclusion Principle]

iPhone难卖,被欧洲反垄断的服务业务也难赚钱了,苹果的日子艰难

什么是混合元编程

态路小课堂丨浅谈优质光模块需要具备的条件!

什么是一致性哈希?可以应用在哪些场景?

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

Based on 10 years of experience in stability assurance, what are the three key questions to be answered in failure recovery?|TakinTalks big coffee sharing

软件测试之发现和解决bug

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

微信UI在线聊天源码 聊天系统PHP采用 PHP 编写的聊天软件,简直就是一个完整的迷你版微信
随机推荐
D - I Hate Non-integer Number(背包dp)
使用ffmpeg来查看视频的信息,fps,和width,height
脚本语言Lua的基础知识总结
模型运营是做什么的(概念模型数据库)
PAT 1162 Postfix Expression(25)
DDL和DML的含义与区别「建议收藏」
The little thing about Request reuse.The research is understood, and I will report it to you.
「计算复杂性」理论奠基人Juris Hartmanis逝世,曾获93年图灵奖
mysql的基本使用
ABC260 E - At Least One(双指针)
重磅!国内首个开放式在线绘图平台Figdraw突破10万用户!发布《奖学金激励计划》:最高5000元!...
Windows 安装PostgreSQL
【2022蓝帽杯】file_session && 浅入opcode
芝加哥丰田技术学院 | Leveraging Natural Supervision for Language Representation Learning and Generation(利用自然监督进行语言表示学习和生成)
数字孪生北京故宫,元宇宙推进旅游业进程
PyTorch 进阶之路:在 GPU 上训练深度神经网络
快速理解拉格朗日乘子法
超全!全国近90所大学考研报录比汇总!
代理商替代义隆153 Aip4210
拥抱NFV,Istio 1.1 将支持多网络平面