当前位置:网站首页>剑指offer:二叉树中和为某一值的路径(回溯)
剑指offer:二叉树中和为某一值的路径(回溯)
2022-04-22 05:56:00 【wyplj_sir】
题目
输入一棵二叉树和一个整数,打印出二叉树中节点值的和为输入整数的所有路径。从树的根节点开始往下一直到叶节点所经过的节点形成一条路径。
示例
给定如下二叉树,以及目标和 sum = 22
返回:
[ [5,4,11,2], [5,8,4,5] ]
代码
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */
class Solution {
public List<List<Integer>> pathSum(TreeNode root, int sum) {
List<List<Integer>> result = new ArrayList<>();
List<Integer> list = new ArrayList<>();
dfs(root, sum, result, list);
return result;
}
public void dfs(TreeNode root, int target, List<List<Integer>> result, List<Integer> list){
if(root == null){
return;
}
list.add(root.val);
target = target - root.val;
if(target == 0 && root.left == null && root.right == null){
List<Integer> temp = new ArrayList<>();
for(Integer val : list){
temp.add(val);
}
result.add(temp);
}else{
dfs(root.left, target, result, list);
dfs(root.right, target, result, list);
}
list.remove(list.size()-1);
}
}
版权声明
本文为[wyplj_sir]所创,转载请带上原文链接,感谢
https://blog.csdn.net/wyplj2015/article/details/108759913
边栏推荐
- 倒计时一个月,PGConf.Asia2021亚洲大会最新前瞻,有哪些值得关注的亮点?
- 出海美利坚 不可忽视的未成年人法律红线
- Good news | Kyushu cloud was rated as "Zhejiang high tech enterprise research and development center"
- webService接口编写并发布与webService接口的调用(二)
- TCP和UDP区别详解
- 数美科技未成年人保护解决方案重磅上线,开启未成年人网络护航新时代
- 使用kubeadm安装kuberneters
- 2021-07-07
- Escort · the future 𞓜 digital risk control summit of digital America 2022 officially set off
- OLAP和OLTP的区别及所对应模型(基础知识)
猜你喜欢
随机推荐
Copu helped Peking University Graduate open source public elective course - Open Source PostgreSQL R & D course successfully enter Peking University
PostgreSQL 13.3, 12.7, 11.12, 10.17 and 9.6.22 have been released!
Flink源码之StreamExecutionEnvironment
解决Windows2012 R2下安装PostgreSQL报错的问题
Hit the pain point directly, Kyushu cloud 5g private network helps FAW Fusheng intelligent logistics construction
scala中的伴生类和伴生对象
《通用数据保护条例》(GDPR)系列解读一:如何判断出海企业是否受GDPR管辖?
MYSQL 使用OR查询SQL执行很慢
The sixth anniversary of digital technology pays tribute to you behind it
Great! Kyushu cloud edge computing management platform has been certified by the national authority
出海美利坚 不可忽视的未成年人法律红线
数美科技未成年人保护解决方案重磅上线,开启未成年人网络护航新时代
滚动条的多种样式
利用win自带功能让处于同一局域网的两个电脑之间互传文件(速度和本地磁盘间互传相同)
企业风控如何搭建四大体系,实现全局防控?
Redis持久化
携手强化「内容审核」能力,融云与数美科技达成战略合作!
使用kubeadm安装kuberneters
Shumei technology has obtained the international certification of ISO / IEC 27701 privacy information management system
grpc长连接keepalive










