当前位置:网站首页>剑指 Offer 34. 二叉树中和为某一值的路径
剑指 Offer 34. 二叉树中和为某一值的路径
2022-07-20 19:51:00 【愈努力俞幸运】
一看就是,dfs搜到底,
走到叶子节点后看这条路径的和是否为target。
那怎么判断何为多少呢?可以把target当作一个递归参数,这样就可以看和为多少?
那怎么记录路径呢?
节点A去往下搜时,就把这个节点A加入路径中,如果节点A,后面所有路径都不满足,就把这个节点弹出去,如果节点A后面有路径满足,将path加入到结果列表中,节点A弹出去,因为,节点A已经看完了
dfs(root, tar) 函数:
递推参数: 当前节点 root ,当前目标值 tar 。
终止条件: 若节点 root 为空,则直接返回。
递推工作:
路径更新: 将当前节点值 root.val 加入路径 path ;
目标值更新: tar = tar - root.val(即目标值 tar 从 sum 减至 0 );
路径记录: 当 ① root 为叶节点 且 ② 路径和等于目标值 ,则将此路径 path 加入 res 。
先序遍历: 递归左 / 右子节点。
路径恢复: 向上回溯前,需要将当前节点从路径 path 中删除,即执行 path.pop() 。
值得注意的是,记录路径时若直接执行 res.append(path) ,则是将 path 对象加入了 res ;后续 path 改变时, res 中的 path 对象也会随之改变。
正确做法:res.append(list(path)) ,相当于复制了一个 path 并加入到 res 。
不明白的可以参考python中的引用_愈努力俞幸运的博客-CSDN博客_python 引用
运行个小例子
lst=[1,2,3,4,5]
lst1=list(lst)
lst.pop()
print(lst,lst1)
class Solution:
def pathSum(self, root, target):
res,path=[],[]
def dfs(node,tar):
if not node:return
path.append(node.val)
tar-=node.val
if not node.left and not node.right and tar==0:
res.append(list(path))
dfs(node.left,tar)
dfs(node.right,tar)
path.pop()
dfs(root,target)
return res
边栏推荐
- 源码安装PostgreSQL 13.1
- Teach you to speculate in stocks 2: there is no Zhuang family, but only winners and losers
- 和客户沟通的总结
- Go语言 包管理
- For a single document BCG program, why is the title of the toolbar set at the end of cmainframe:: oncreate? Why is it invalid?
- 为cv::Point 重载了<,但VS2010找不到
- The DBA road of small town problem makers
- Oserror: [winerror 1455] the page file is too small to complete the operation.
- rce(无回显)
- openGauss之简单使用Plan hint进行SQL调优
猜你喜欢
简易学生管理系统项目:(增、删、查、改、模糊查、分页查、上传、下载、视频导入、当前系统时间) --- 《附源码》
Rt-thread-2022 summer camp - learning summary - day 3 (thread synchronization)
百度面试题——判断一个正整数是否为2的K次方
One bite of Stream(7)
The simplest implementation of throttling and anti chattering
2022年7月俄罗斯数据库排行榜:ClickHouse雄踞榜首,GigaBASE摘得榜眼
PCL calculates point cloud roughness
百度飞桨EasyDL助力高海拔光伏电站巡检效率提升98%
Dc-3-range practice
Oserror: [winerror 1455] the page file is too small to complete the operation.
随机推荐
幼儿园学费比较
Win11 Excel文件变成白板图标怎么解决?
百度飞桨EasyDL助力高海拔光伏电站巡检效率提升98%
Teach you to speculate in stocks 2: there is no Zhuang family, but only winners and losers
High score technical document sharing of ink Sky Wheel - Database Security (48 in total)
Redis实现分布式限流(学习笔记
Is it OK to open an account with flush? Is it safe?
(22) blender source code analysis: mouse down message to window call process
《PyTorch深度学习实践》学习笔记:循环神经网络(高级篇)
Hisilicon AI chip (hi35xx): image JPG to BGR upgrade
STL notes (XIII): relevance container - mapping
JVM startup process
BCG localization
For development, user experience is the ultimate King (Performance Optimization)
Win11 cannot find gpedit What about MSc? Win11 cannot open gpedit MSc solution tutorial
One bite of Stream(7)
redis6.0集群搭建
简易学生管理系统项目:(增、删、查、改、模糊查、分页查、上传、下载、视频导入、当前系统时间) --- 《附源码》
消息称苹果继续向俄罗斯市场交付产品:不进行售卖,只用于退换货
单元测试,写起来到底有多痛?你会了吗