当前位置:网站首页>二叉树递归套路总结
二叉树递归套路总结
2022-07-05 22:50:00 【明朗晨光】
之前所有用到二叉树递归套路的时间复杂度都是 O ( N ) O(N) O(N),其中 N N N 是二叉树的节点个数,且都是最优解。
某个节点从左右孩子获取信息,然后整合到该节点,此时的左右孩子已经不需要了,而该节点的父节点也是重复这个过程,整个过程相当于后序遍历,在树上做动态规划,所以叫做树型dp。
这个套路包括两个层次:
思想提醒
目标如何实现:X 为根节点的二叉树如何实现目标?
实现手段:向左右树要信息,列举可能性,这个可能性一定是基于从左右树要来的信息(常数时间内可以得到的),加工出来的同等量级的信息也是常数时间的。
设计信息体,分析可能性,常见的分类是 “与目标 X 有关” 和 “与目标 X 无关”。模板
① 设计Info
信息体;
②process
函数:process
函数一定要返回Info
;遇到空的时候,如果值不好设置就返回空,如果好设置就设置;
③默认先得到左树信息,然后得到右树信息;
④分析完可能性后,把 X 需要的信息都加工出来,这是高度模板化的。
这个套路可以解决绝大多数的二叉树问题尤其是树型dp问题,本质是利用 递归遍历二叉树 的便利性。
整个流程总结如下:
1)假设以 X 节点为根,假设可以向 X 左树和 X 右树要任何信息
2)在上一步的假设下,讨论以 X 为根节点的树,得到答案的可能性(最重要)
3)列出所有可能性后,确定到底需要向左树和右树要什么样的信息
4)把左树信息和右树信息求全集,就是任何一棵子树都需要返回的信息S
5)递归函数都返回S,每一棵子树都这么要求
6)写代码,在代码中考虑如何把左树的信息和右树信息整合出整棵树的信息
边栏推荐
- Solve the problem of "no input file specified" when ThinkPHP starts
- TCC of distributed solutions
- [digital signal denoising] improved wavelet modulus maxima digital signal denoising based on MATLAB [including Matlab source code 1710]
- Global and Chinese market of diesel fire pump 2022-2028: Research Report on technology, participants, trends, market size and share
- Metasploit(msf)利用ms17_010(永恒之蓝)出现Encoding::UndefinedConversionError问题
- 谷歌地图案例
- 一文搞定垃圾回收器
- Nacos installation and service registration
- Media query: importing resources
- Distributed solution selection
猜你喜欢
Double pointer of linked list (fast and slow pointer, sequential pointer, head and tail pointer)
audiopolicy
Tensor attribute statistics
Using LNMP to build WordPress sites
Vcomp110.dll download -vcomp110 What if DLL is lost
一文搞定JVM常见工具和优化策略
Common model making instructions
Getting started stm32--gpio (running lantern) (nanny level)
[speech processing] speech signal denoising based on Matlab GUI Hanning window fir notch filter [including Matlab source code 1711]
实现反向代理客户端IP透传
随机推荐
openresty ngx_ Lua regular expression
一文搞定class的微观结构和指令
Global and Chinese markets for welding products 2022-2028: Research Report on technology, participants, trends, market size and share
Expectation, variance and covariance
Masked Autoencoders Are Scalable Vision Learners (MAE)
openresty ngx_ Lua request response
Douban scoring applet Part-2
Three.JS VR看房
数据库基础知识(面试)
Nanjing: full use of electronic contracts for commercial housing sales
【Note17】PECI(Platform Environment Control Interface)
【Note17】PECI(Platform Environment Control Interface)
VIM tail head intercept file import
openresty ngx_lua正则表达式
All expansion and collapse of a-tree
Vision Transformer (ViT)
Negative sampling
Tiktok__ ac_ signature
2022 registration examination for safety management personnel of hazardous chemical business units and simulated reexamination examination for safety management personnel of hazardous chemical busines
How to quickly understand complex businesses and systematically think about problems?