当前位置:网站首页>【二叉树】统计值等于子树平均值的节点数
【二叉树】统计值等于子树平均值的节点数
2022-08-06 03:56:00 【豪冷啊】
0x00 题目
给你一棵二叉树的根节点 root
找出并返回满足要求的节点数
要求节点的值等于其 子树 中值的 平均值
注意:n 个元素的平均值可以由 n 个元素 求和 然后再除以 n
并 向下舍入 到最近的整数root 的 子树 由 root 和它的所有后代组成
0x01 思路
要获取某个子树的个数以及所有节点值的和
就需要使用后序遍历方式
总和 = 当前节点值 + 左子树的和 + 右子树的和
个数 = 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 averageOfSubtree(_ root: TreeNode?) -> Int {
guard let root = root else { return 0 }
var res: Int = 0
func dfs(_ root: TreeNode?) -> (Int, Int) {
guard let root = root else { return (0,0) }
let left = dfs(root.left)
let right = dfs(root.right)
// 后序遍历
// 总和
let sum = left.0 + right.0 + root.val
// 个数
let count = left.1 + right.1 + 1
// 平均值
let average = sum / count
// 相等则统计
if (average == root.val) { res += 1}
return (sum, count)
}
_ = dfs(root)
return res
}
0x03 我的小作品
欢迎体验我的作品之一:小笔记-XNote
笔记好帮手~App Store 搜索即可~
边栏推荐
- P1404 平均数
- Introduction to Elliptic Curves (4): Elliptic Curve Security, Compared with RSA
- 3.cuBLAS开发指南中文版--cuBLAS数据类型引用
- What are the big events on Tmall in August 2022?
- LeetCode:623. 在二叉树中增加一行【DFS or BFS】
- 物联网协议概述
- 1187 Candy, xtu
- 洛谷 : P1020 [NOIP1999 普及组] 导弹拦截
- Netcore——Result
- Programmer's first day at work | Daily anecdote
猜你喜欢

Wang Qi, Secretary of the Party Committee and President of Shanghai Pudong Development Bank Changsha Branch, and Jiang Junwen, President of Huarong Xiangjiang Bank, visited Kylin Principal for investi

The delivery language set in the Google Ads background, if English is set, does it mean that the user is using English?

Smart Contract Security - Random Numbers

经典sql例子

FluentValidation

If you like us, it is better to join us: come and contribute, the payment is reliable!

jvm: synchronized关键字不同用法产生不同的字节码

xctf attack and defense world web master advanced area command_execution

电赛电源类题型之问

89. (home of cesium) cesium aggregation graph (custom image)
随机推荐
Which browser has fewer ads?Multi-Royal Safe Browser Light Experience
洛谷 :P1104 生日
我所理解liunx下的原子操作
Fragment的四种跳转方式
What are solid pneumatic tires?
Sring中常用注解归纳
leetcode:1374. 生成每种字符都是奇数个的字符串
Failed to save image in R language ggplot2 loop
喜欢我们不如加入我们:来投稿吧,稿酬靠谱!
译文推荐|深入解析 BookKeeper 协议模型与验证
谷歌分析中的转化目标设置后,大概多久能显示在Google adwords后台?
Introduction to Elliptic Curves (4): Elliptic Curve Security, Compared with RSA
【Translation】Serverless Architecture: Pros and Cons
Web3.exceptions.ExtraDataLengthError
洛谷 : P1020 [NOIP1999 普及组] 导弹拦截
【翻译】无服务器架构:利与弊
R语言ggplot2循环中保存图片失败问题
【LaTex】 - 对齐符号&的用法,换行符\\的用法,Misplaced &错误怎么解决
2022年天猫8月份有什么大的活动?
Literature Reading---Analysis of Genome Haplotypes and Genome Stability and Creeping of Common Bermudagrass Yangjiang