当前位置:网站首页>【二叉树】路径总和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);
}
}
边栏推荐
猜你喜欢
[LiteratureReview]Optimal and Robust Category-level Perception: Object Pose and Shape Estimation f
What is consistent hashing?In what scenarios can it be applied?
多线程案例——阻塞式队列
Windows 安装PostgreSQL
全球都热炸了,谷歌服务器已经崩掉了
170页6万字智慧能源管理平台建设方案书
性能测试入门指南
How does the SAP ABAP OData service support the Create operation trial version
Batch replace tables in Word with pictures and save
A Beginner's Guide to Performance Testing
随机推荐
RGB系列开发稳定响应快速灯带拾音灯氛围灯等应用定制方案
leetcode:1201. 丑数 III【二分 + 数学 + 容斥原理】
CCS软件安装教程(超级详细)「建议收藏」
对标丰田!蔚来又一新品牌披露:产品价格低于20万
热心肠:关于肠道菌群和益生菌的10个观点
脚本语言Lua的基础知识总结
树和二叉树的转换
34、树莓派进行人体姿态检测并进行语音播报
[深入研究4G/5G/6G专题-47]: 5G Link Adaption链路自适应-3-下行链路自适应DLLA-PDSCH信道
The little thing about Request reuse.The research is understood, and I will report it to you.
How do we do full-link grayscale on the database?
态路小课堂丨浅谈优质光模块需要具备的条件!
tensorflow2.0手写数字识别(tensorflow手写体识别)
什么是混合元编程
计算器:中缀表达式转后缀表达式
关于Request复用的那点破事儿。研究明白了,给你汇报一下。
「计算复杂性」理论奠基人Juris Hartmanis逝世,曾获93年图灵奖
JMP Pro 16.0 software installation package download and installation tutorial
考研大事件!这6件事考研人必须知道!
What Can Service Mesh Learn from SDN?