当前位置:网站首页>【二叉树】根到叶路径上的不足节点
【二叉树】根到叶路径上的不足节点
2022-07-05 16:40:00 【豪冷啊】
0x00 题目
给定一棵二叉树的根 root
考虑它所有从根
到任何叶
路径
假如通过节点 node
的每种可能的 “根-叶”
路径上值的总和
全都小
于给定的 limit
则该节点被称之为不足节点
,需要被删除
请你删除所有不足节点,并返回生成的二叉树的根
0x01 思路
因为要计算从根到叶
的总和
所以使用深度
优先的遍历算法
节点 node
被删除的条件是sum + node.val < limit
sum
为路径上 node
前面所有节点的和
反过来讲
每经过一个节点,可以更新 limit
limit - node.val
当 node.val < limit
时
就要被删除
0x02 解法
语言:Swift
树节点:TreeNode
public class TreeNode {
public var val: Int
public var left: TreeNode?
public var right: TreeNode?
public init() { self.val = 0; self.left = nil; self.right = nil; }
public init(_ val: Int) { self.val = val; self.left = nil; self.right = nil; }
public init(_ val: Int, _ left: TreeNode?, _ right: TreeNode?) {
self.val = val
self.left = left
self.right = right
}
}
解法:
func sufficientSubset(_ root: TreeNode?, _ limit: Int) -> TreeNode? {
guard let root = root else { return nil }
let left = root.left
let right = root.right
// 到达叶子节点
if left == nil && right == nil {
return root.val >= limit ? root : nil
}
// 经过一个节点,减小
let res = limit - root.val
if left != nil {
root.left = sufficientSubset(left, res)
}
if right != nil {
root.right = sufficientSubset(right, res)
}
// 更新左右节点后,都为空
// 说明以当前节点为根,到叶子节点的路径总和 小于 limit
// 所以当前节点也要被删除
if root.left == nil && root.right == nil {
return nil
}
return root
}
0x03 我的作品
欢迎体验我的作品之一:小五笔 86 版
五笔学习好帮手App Store
搜索即可~
边栏推荐
- 【性能测试】全链路压测
- Jarvis OJ simple network management protocol
- 国产芯片产业链两条路齐头并进,ASML真慌了而大举加大合作力度
- Embedded-c language-6
- 【Web攻防】WAF检测技术图谱
- PHP人才招聘系统开发 源代码 招聘网站源码二次开发
- Read the basic grammar of C language in one article
- Deep dive kotlin synergy (XXI): flow life cycle function
- The first EMQ in China joined Amazon cloud technology's "startup acceleration - global partner network program"
- 深潜Kotlin协程(二十一):Flow 生命周期函数
猜你喜欢
Jarvis OJ Flag
Deep learning plus
The second day of learning C language for Asian people
飞桨EasyDL实操范例:工业零件划痕自动识别
兰空图床苹果快捷指令
High number | summary of calculation methods of volume of rotating body, double integral calculation of volume of rotating body
thinkphp模板的使用
CMake教程Step1(基本起点)
[61dctf]fm
采用药丸屏的iPhone14或引发中国消费者的热烈抢购
随机推荐
干货!半监督预训练对话模型 SPACE
Explain in detail the functions and underlying implementation logic of the groups sets statement in SQL
机器学习编译第2讲:张量程序抽象
【729. 我的日程安排錶 I】
C# TCP如何限制单个客户端的访问流量
Thoughtworks 全球CTO:按需求构建架构,过度工程只会“劳民伤财”
Read the basic grammar of C language in one article
[brush questions] effective Sudoku
阈值同态加密在隐私计算中的应用:解读
Deep dive kotlin synergy (XXI): flow life cycle function
高数 | 旋转体体积计算方法汇总、二重积分计算旋转体体积
Writing method of twig array merging
Is it safe to open futures accounts online? Will there be more liars online? Doesn't feel very reliable?
手机开证券账户安全吗?怎么买股票详细步骤
First day of learning C language
Data verification before and after JSON to map -- custom UDF
Embedded-c Language-3
easyNmon使用汇总
Is it safe to open a securities account by mobile phone? Detailed steps of how to buy stocks
Learnopongl notes (I)