当前位置: 首页 > news >正文

Leetcode113. 路径总和 II

力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台

给你二叉树的根节点 root 和一个整数目标和 targetSum ,找出所有 从根节点到叶子节点 路径总和等于给定目标和的路径。

官方题解:力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台

力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台

代码如下:

class Solution {public List<List<Integer>> pathSum(TreeNode root, int targetSum) {List<List<Integer>> res = new ArrayList<>();if(root == null) {return res;}List<Integer> path = new ArrayList<>();path.add(root.val);targetSum -= root.val;dfs(root,targetSum,path,res);return res;}public void dfs(TreeNode root,int sum,List<Integer> path,List<List<Integer>> res){if(root.left == null && root.right == null && sum == 0){res.add(new ArrayList<>(path));return;}if(root.left != null) {path.add(root.left.val); sum -= root.left.val;dfs(root.left,sum,path,res);sum += root.left.val;path.remove(path.size()-1);}if(root.right != null) {path.add(root.right.val); sum -= root.right.val;dfs(root.right,sum,path,res);sum += root.right.val;path.remove(path.size()-1);}}
}

 

http://www.lryc.cn/news/162445.html

相关文章:

  • 分布式锁之redis实现
  • Idea中如何在一个项目中引入其他子模块?
  • UDP协议概述
  • Python-tracemalloc-跟踪内存分配
  • 02 CSS技巧
  • Yarn资源调度器
  • android上架备案公钥和md5获取工具
  • SpringBoot系列(12):SpringBoot集成log4j2日志配置
  • HTML事件列表
  • 并发-Executor框架笔记
  • 【C进阶】分析 C/C++程序的内存开辟与柔性数组(内有干货)
  • 深入理解 JVM 之——字节码指令与执行引擎
  • C++:vector
  • Android Automotive编译
  • 什么是50ETF期权开户条件,怎么开期权交易权限?
  • React 从入门到精通——本文来自AI创作助手
  • 【51单片机实验笔记】前篇(三) 模块功能封装汇总(持续更新)
  • Excel VSTO开发4 -其他事件
  • 语音识别数据的采集方法:基本流程数据类型
  • oracle数据库给用户授权DBA权限Oracle查看哪些用户具有DBA权限
  • 024-从零搭建微服务-系统服务(六)
  • Arduino驱动TCS3200传感器(颜色传感器篇)
  • 基于Matlab实现多个数字水印案例(附上源码+数据集)
  • C语言之指针进阶篇(2)
  • C++ 进制转化入门知识(1)
  • 【React】React学习:从初级到高级(四)
  • 微信小程序登录问题(思路简略笔记)
  • Go 锁扩展
  • Docker的简介及安装
  • 安卓核心板的不同核心规格及架构介绍