【LeetCode】637. Average of Levels in Binary Tree 解题报告(Python)
作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.cn/
题目地址:https://leetcode.com/submissions/detail/136579829/
题目描述
Given a non-empty binary tree, return the average value of the nodes on each level in the form of an array.
Example 1:
Input:
3
/ \
9 20
/ \
15 7
Output: [3, 14.5, 11]
Explanation:
The average value of nodes on level 0 is 3, on level 1 is 14.5, and on level 2 is 11. Hence return [3, 14.5, 11].
Note:
- The range of node’s value is in the range of 32-bit signed integer.
题目大意
求二叉树每层的所有节点的平均值
解题方法
方法一:DFS
这个题需要保存每层的节点的和以及每层的节点数。采用DFS
的方式,把每个节点进行遍历,把这个节点加到对应层中去。每层使用两个数字,第一个数字保存所有节点的和,第二个数字保存有多少个节点。
注意一个小问题,节点为空的时候要return,否则下面node为None,出现错误。
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def averageOfLevels(self, root):
"""
:type root: TreeNode
:rtype: List[float]
"""
info = [] # the first element is sum of the level,the second element is nodes in this level
def dfs(node, depth=0):
if not node:
return
if len(info) <= depth:
info.append([0, 0])
info[depth][0] += node.val
info[depth][1] += 1
# print(info)
dfs(node.left, depth + 1)
dfs(node.right, depth + 1)
dfs(root)
return [s / float(c) for s,c in info]
二刷。直接使用数组保存每层所有节点的值,最后需要做个求平均数的处理。
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def averageOfLevels(self, root):
"""
:type root: TreeNode
:rtype: List[float]
"""
res = []
self.getLevel(root, 0, res)
return [sum(line) / float(len(line)) for line in res]
def getLevel(self, root, level, res):
if not root:
return
if level >= len(res):
res.append([])
res[level].append(root.val)
self.getLevel(root.left, level + 1, res)
self.getLevel(root.right, level + 1, res)
方法二:BFS
其实层次遍历使用BFS比使用DFS更加简单高效。因为每层遍历结束之后,已经知道了这一行的所有数字,所以可以直接求平均数,然后放入到结果中去,而不用最后才求平均数了。
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def averageOfLevels(self, root):
"""
:type root: TreeNode
:rtype: List[float]
"""
que = collections.deque()
res = []
que.append(root)
while que:
size = len(que)
row = []
for _ in range(size):
node = que.popleft()
if not node:
continue
row.append(node.val)
que.append(node.left)
que.append(node.right)
if row:
res.append(sum(row) / float(len(row)))
return res
日期
2018 年 1 月 17 日
2018 年 11 月 9 日 —— 睡眠可以
【LeetCode】637. Average of Levels in Binary Tree 解题报告(Python)的更多相关文章
- LeetCode 637 Average of Levels in Binary Tree 解题报告
题目要求 Given a non-empty binary tree, return the average value of the nodes on each level in the form ...
- [LeetCode] 637. Average of Levels in Binary Tree 二叉树的层平均值
Given a non-empty binary tree, return the average value of the nodes on each level in the form of an ...
- LeetCode 637. Average of Levels in Binary Tree二叉树的层平均值 (C++)
题目: Given a non-empty binary tree, return the average value of the nodes on each level in the form o ...
- LeetCode - 637. Average of Levels in Binary Tree
Given a non-empty binary tree, return the average value of the nodes on each level in the form of an ...
- LeetCode 637. Average of Levels in Binary Tree(层序遍历)
Given a non-empty binary tree, return the average value of the nodes on each level in the form of an ...
- 637. Average of Levels in Binary Tree - LeetCode
Question 637. Average of Levels in Binary Tree Solution 思路:定义一个map,层数作为key,value保存每层的元素个数和所有元素的和,遍历这 ...
- 【Leetcode_easy】637. Average of Levels in Binary Tree
problem 637. Average of Levels in Binary Tree 参考 1. Leetcode_easy_637. Average of Levels in Binary T ...
- 【LeetCode】662. Maximum Width of Binary Tree 解题报告(Python)
[LeetCode]662. Maximum Width of Binary Tree 解题报告(Python) 标签(空格分隔): LeetCode 题目地址:https://leetcode.co ...
- 【LeetCode】297. Serialize and Deserialize Binary Tree 解题报告(Python)
[LeetCode]297. Serialize and Deserialize Binary Tree 解题报告(Python) 标签: LeetCode 题目地址:https://leetcode ...
随机推荐
- X-MagicBox-820的luatOS之路连载系列6
继上次用Qt实现了显示地图和MQTT通信之后(X-MagicBox-820的luatOS之路连载系列5),说是要研究下地图的开放接口,也看了标记点和线的方法(地图上自定义标记点和轨迹线的实现).这次就 ...
- 【风控算法】一、变量分箱、WOE和IV值计算
一.变量分箱 变量分箱常见于逻辑回归评分卡的制作中,在入模前,需要对原始变量值通过分箱映射成woe值.举例来说,如"年龄"这一变量,我们需要找到合适的切分点,将连续的年龄打散到不同 ...
- 为构建大型复杂系统而生的微服务框架 Erda Infra
作者|宋瑞国(尘醉) 来源|尔达 Erda 公众号 导读:Erda Infra 微服务框架是从 Erda 项目演进而来,并且完全开源.Erda 基于 Erda Infra 框架完成了大型复杂项目的 ...
- c++ cmake及包管理工具conan简单入门
cmake是一个跨平台的c/c++工程管理工具,可以通过cmake轻松管理我们的项目 conan是一个包管理工具,能够自动帮助我们下载及管理依赖,可以配合cmake使用 这是一个入门教程,想深入了解的 ...
- js正则表达式之密码强度验证
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...
- 源码分析-NameServer
架构设计 消息中间件的设计思路一般是基于主题订阅发布的机制,消息生产者(Producer)发送某一个主题到消息服务器,消息服务器负责将消息持久化存储,消息消费者(Consumer)订阅该兴趣的主题,消 ...
- Linux基础命令---dig工具
dig dig是一个DNS查询工具,多数管理员会使用dig命令来解决DNS的问题. 此命令的适用范围:RedHat.RHEL.Ubuntu.CentOS.Fedora. 1.语法 di ...
- Android 清除本地缓存
主要功能:清除内.外缓存,清除数据库,清除Sharepreference,清除files和清除自定义目录 public class DataCleanManager { //清除本应用内部缓存(/da ...
- jmeter设置参数化
设置参数化方法有3种 第一种: 1.打开 jmeter,导入badboy录制的脚本 导入后记得选择"step"右键选择change controller ->逻辑控制器-&g ...
- Hadoop生态圈学习-1(理论基础)
一.大数据技术产生的背景 1. 计算机和信息技术(尤其是移动互联网)的迅猛发展和普及,行业应用系统的规模迅速扩大(用户数量和应用场景,比如facebook.淘宝.微信.银联.12306等),行业应用所 ...