当前位置:网站首页>【二叉树】在二叉树中分配硬币
【二叉树】在二叉树中分配硬币
2022-06-28 13:48:00 【豪冷啊】
0x00 题目
给定一个有 N 个结点的二叉树的根结点 root
树中的每个结点上都对应有 node.val 枚硬币
并且总共有 N 枚硬币
在一次移动中,我们可以选择两个相邻的结点
然后将一枚硬币从其中一个结点移动到另一个结点
移动可以是从父结点到子结点,或者从子结点移动到父结点
返回使每个结点上只有一枚硬币所需的移动次数
0x01 思路
每个节点都需要有一枚硬币
所以节点 r 所需的硬币是 r.val - 1r.val > 1 时
说明要把多余的硬币移走r.val == 0 时
说明需要从别的地方移入硬币
以 r 为根的节点
所需的总硬币数为r.val - 1 + 左子树所需 + 右子树所需
所以需要使用后序遍历方式
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 distributeCoins(_ root: TreeNode?) -> Int {
var res = 0
func need(_ root: TreeNode?) -> Int {
guard let r = root else { return 0 }
// 左子树
let left = need(r.left)
// 右子树
let right = need(r.right)
// 以 r 为根节点的子树,总共所需的移动次数
res += abs(left) + abs(right) + r.val - 1
// 当前树所需要的硬币数,正,移出,负,移入
let out = left + right + r.val - 1
return out
}
_ = need(root)
return res
}
0x03 我的作品
欢迎体验我的作品之一:小五笔 86 版
五笔学习好帮手~App Store 搜索即可~
边栏推荐
- Oracle 云基础设施扩展分布式云服务,为组织提供更高的灵活性和可控性
- 《畅玩NAS》家庭 NAS 服务器搭建方案「建议收藏」
- 《蛤蟆先生去看心里医生》阅读笔记
- Writing skills of resume
- 木兰开放作品许可证1.0面向社会公开征求意见
- 2022年中国运维安全产品市场规模及发展趋势预测分析
- Class structure in C language - dot
- How vscade sets auto save code
- To be the Italian Islander? Liuqiangdong cashed out 6.6 billion yuan in two months and made a one-time 560million "emergency transfer" to buy the European maritime Palace
- 抢做意大利岛主?刘强东两月套现66亿 疑一次性5.6亿“紧急转账”急购欧洲海上皇宫
猜你喜欢

Stackoverflow 2022 database annual survey

Hubble数据库x某股份制商业银行:冠字号码管理系统升级,让每一张人民币都有 “身份证”

众昂矿业着眼氟化工产业,布局新能源产业链

中国数据库技术大会(DTCC)特邀科蓝SUNDB数据库专家精彩分享

Oracle 云基础设施扩展分布式云服务,为组织提供更高的灵活性和可控性

开源社邀您参加OpenInfra Days China 2022,议题征集进行中~

设计人工智能产品:技术可能性、用户合意性、商业可行性

Mobile web training -flex layout test question 1

APP冷热启动专项测试

New product experience: Alibaba cloud's new generation of local SSD instance I4 open beta
随机推荐
Forecast and Analysis on market scale and development trend of China's operation and maintenance security products in 2022
1015. picking flowers
Introduction to PWN (1) binary Basics
Hematemesis recommends 17 "wheels" to improve development efficiency
Make an ink screen electronic clock, cool!
MySQL multi table joint query
(original) [Maui] realize "floating action button" step by step
2022年中国运维安全产品市场规模及发展趋势预测分析
StackOverflow 2022数据库年度调查
What is generics and how to use generics analysis
Pytorch main modules
Talk about exception again -- what happens when an exception is thrown?
2.01 backpack problem
再談exception——异常拋出時會發生什麼?
How to solve the data inconsistency between redis and MySQL?
单元测试 CI/CD
China Database Technology Conference (DTCC) specially invited experts from Kelan sundb database to share
正则匹配数字,英文以及英文符号
欧拉恒等式:数学史上的真正完美公式!
开源社邀您参加OpenInfra Days China 2022,议题征集进行中~