当前位置:网站首页>【二叉树】根到叶路径上的不足节点
【二叉树】根到叶路径上的不足节点
2022-07-05 16:40:00 【豪冷啊】
0x00 题目
给定一棵二叉树的根 root
考虑它所有从根到任何叶 路径
假如通过节点 node 的每种可能的 “根-叶”
路径上值的总和全都小于给定的 limit
则该节点被称之为不足节点,需要被删除
请你删除所有不足节点,并返回生成的二叉树的根
0x01 思路
因为要计算从根到叶的总和
所以使用深度优先的遍历算法
节点 node 被删除的条件是sum + node.val < limitsum 为路径上 node 前面所有节点的和
反过来讲
每经过一个节点,可以更新 limitlimit - 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 搜索即可~
边栏推荐
猜你喜欢

国产芯片产业链两条路齐头并进,ASML真慌了而大举加大合作力度
![[team PK competition] the task of this week has been opened | question answering challenge to consolidate the knowledge of commodity details](/img/d8/a367c26b51d9dbaf53bf4fe2a13917.png)
[team PK competition] the task of this week has been opened | question answering challenge to consolidate the knowledge of commodity details

ternary operator

Embedded UC (UNIX System Advanced Programming) -2

thinkphp模板的使用

腾讯音乐上线新产品“曲易买”,提供音乐商用版权授权

【性能测试】jmeter+Grafana+influxdb部署实战

Embedded -arm (bare board development) -1

If you can't afford a real cat, you can use code to suck cats -unity particles to draw cats

【729. 我的日程安排錶 I】
随机推荐
Embedded-c Language-2
调查显示传统数据安全工具面对勒索软件攻击的失败率高达 60%
网站页面禁止复制内容 JS代码
Deep dive kotlin synergy (XXI): flow life cycle function
麻烦问下,DMS中使用Redis语法是以云数据库Redis社区版的命令为参考的嘛
齐宣王典故
微信公众号网页授权登录实现起来如此简单
深潜Kotlin协程(二十一):Flow 生命周期函数
[team PK competition] the task of this week has been opened | question answering challenge to consolidate the knowledge of commodity details
激动人心!2022开放原子全球开源峰会报名火热开启!
编译libssh2报错找不到openssl
Games101 notes (III)
Machine learning compilation lesson 2: tensor program abstraction
Embedded UC (UNIX System Advanced Programming) -2
深耕5G,芯讯通持续推动5G应用百花齐放
浏览器渲染原理以及重排与重绘
The first lesson of EasyX learning
China Radio and television officially launched 5g services, and China Mobile quickly launched free services to retain users
美国芯片傲不起来了,中国芯片成功在新兴领域夺得第一名
The survey shows that the failure rate of traditional data security tools in the face of blackmail software attacks is as high as 60%