当前位置:网站首页>【二叉树】根到叶路径上的不足节点
【二叉树】根到叶路径上的不足节点
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
搜索即可~
边栏推荐
猜你喜欢
The two ways of domestic chip industry chain go hand in hand. ASML really panicked and increased cooperation on a large scale
CMake教程Step2(添加库)
Embedded UC (UNIX System Advanced Programming) -1
Get ready for the pre-season card game MotoGP ignition champions!
Hiengine: comparable to the local cloud native memory database engine
Solution of vant tabbar blocking content
High number | summary of calculation methods of volume of rotating body, double integral calculation of volume of rotating body
精准防疫有“利器”| 芯讯通助力数字哨兵护航复市
CMake教程Step1(基本起点)
Embedded -arm (bare board development) -1
随机推荐
腾讯音乐上线新产品“曲易买”,提供音乐商用版权授权
Yarn common commands
Use JDBC technology and MySQL database management system to realize the function of course management, including adding, modifying, querying and deleting course information.
麻烦问下,DMS中使用Redis语法是以云数据库Redis社区版的命令为参考的嘛
CMake教程Step4(安装和测试)
[team PK competition] the task of this week has been opened | question answering challenge to consolidate the knowledge of commodity details
CMake教程Step1(基本起点)
Scratch colorful candied haws Electronic Society graphical programming scratch grade examination level 3 true questions and answers analysis June 2022
Judge whether a number is a prime number (prime number)
Solution of vant tabbar blocking content
Writing method of twig array merging
CMake教程Step6(添加自定义命令和生成文件)
ECU简介
Games101 notes (III)
【性能测试】全链路压测
网站页面禁止复制内容 JS代码
Application of threshold homomorphic encryption in privacy Computing: Interpretation
【机器人坐标系第一讲】
Jarvis OJ Webshell分析
IDC报告:腾讯云数据库稳居关系型数据库市场TOP 2!