当前位置:网站首页>剑指Offer 34.二叉树中和为某一值的路径 dfs+回溯
剑指Offer 34.二叉树中和为某一值的路径 dfs+回溯
2022-08-02 03:33:00 【HotRabbit.】
题目
给你二叉树的根节点 root
和一个整数目标和 targetSum
,找出所有 从根节点到叶子节点 路径总和等于给定目标和的路径。
叶子节点 是指没有子节点的节点。
示例 1:
输入:root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22
输出:[[5,4,11,2],[5,8,4,5]]
示例 2:
输入:root = [1,2,3], targetSum = 5
输出:[]
示例 3:
输入:root = [1,2], targetSum = 0
输出:[]
提示:
- 树中节点总数在范围
[0, 5000]
内 -1000 <= Node.val <= 1000
-1000 <= targetSum <= 1000
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/er-cha-shu-zhong-he-wei-mou-yi-zhi-de-lu-jing-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路
dfs+回溯算法,图中右边的线都是回溯的操作。每次到新节点都会在队列尾部添加元素,继续向左、右节点遍历到底,如果当前节点是上一个节点的左节点,回溯上一个节点之后继续遍历右节点,再进行回溯。
题解
class Solution {
List<List<Integer>> lists = new LinkedList<List<Integer>>();
Deque<Integer> path = new LinkedList<>();
public List<List<Integer>> pathSum(TreeNode root, int target) {
dfs(root,target);
return lists;
}
public void dfs(TreeNode root ,int target){
if (root == null){
return;
}
path.offerLast(root.val);
target -= root.val;
if (root.left == null && root.right == null && target == 0){
lists.add(new LinkedList<Integer>(path));
}
dfs(root.left,target);
dfs(root.right,target);
path.pollLast();//回溯
}
}
边栏推荐
- 408-Binary tree-preorder inorder postorder level traversal
- 【网络基础】浏览器输入一个URL之后,都发生了什么(详细讲解)
- Comparative analysis of mobile cloud IoT pre-research and Alibaba Cloud development
- 【plang 1.4.6】Plang高级编程语言(发布)
- 本地数据库 sqlite3 编译和使用
- Introduction and mock implementation of list:list
- 【Arduino connects SD card module to realize data reading and writing】
- Chrome 里的小恐龙游戏是怎么做出来的?
- PCB Design Ideas
- 【Connect the heart rate sensor to Arduino to read the heart rate data】
猜你喜欢
随机推荐
使用飞凌嵌入式IMX6UL-C1板子——qt+opencv环境搭建
基础IO(上):文件管理和描述符
Comparative analysis of OneNET Studio and IoT Studio
本地数据库 sqlite3 编译和使用
MOS管开关原理及应用详解
Compatible with C51 and STM32 Keil5 installation method
将ORCAD原理图导入allegro中进行PCB设计
idea中创建jsp项目详细步骤
HDMI转MIPI CSI东芝转换芯片-TC358743XBG/TC358749XBG
进程(番外):自定义shell命令行解释器
Website development plan research
【详解】线程池及其自定义线程池的实现
振芯科技GM8285C:功能TTL转LVDS芯片简介
TC358860XBG BGA65 东芝桥接芯片 HDMI转MIPI
MPU6050 accelerometer and gyroscope sensor is connected with the Arduino
【科普贴】SPI接口详解
【多线程】线程安全保护机制
GM8775C MIPI转LVDS调试心得分享
引擎开发日志:OpenGL资源多线程加载
Altium Designer基础知识