【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 ...
随机推荐
- Linux—查看内核版本、系统版本、系统位数
一.查看内核版本命令: 1) [root@q1test01 ~]# cat /proc/version Linux version 2.6.9-22.ELsmp (bhcompile@crowe. ...
- 48-Merge Sorted Array
$88. Merge Sorted Array My Submissions QuestionEditorial Solution Total Accepted: 98885 Total Submis ...
- gcc 引用math 库 编译的问题 解决方法
1.gcc app.c -lm 其中lm表示的是连接 m forlibm.so / libm.a表示你想要的库 abc for libabc.so / libabc.a 其中.a表示的是静态链接库 . ...
- Python中的随机采样和概率分布(二)
在上一篇博文<Python中的随机采样和概率分布(一)>(链接:https://www.cnblogs.com/orion-orion/p/15647408.html)中,我们介绍了Pyt ...
- 巩固javaweb的第二十五天
常用的验证 1. 非空验证 // 验证是否是空 function isNull(str) { if(str.length==0) return true; else return false; } 2 ...
- 【Reverse】每日必逆0x03
BUU-刮开有奖 附件:https://files.buuoj.cn/files/abe6e2152471e1e1cbd9e5c0cae95d29/8f80610b-8701-4c7f-ad60-63 ...
- Docker学习(六)——Dockerfile文件详解
Docker学习(六)--Dockerfile文件详解 一.环境介绍 1.Dockerfile中所用的所有文件一定要和Dockerfile文件在同一级父目录下,可以为Dockerfile父目录的子目录 ...
- Docker 生产环境之配置容器 - 自动启动容器
原文地址 Docker 提供了重启策略,以控制容器在退出时是否自动启动,或在 Docker 重新启动时自动启动.重启策略可确保链接的容器以正确的顺序启动.Docker 建议使用重启策略,并避免使用流程 ...
- Default Constructors
A constructor without any arguments or with default value for every argument, is said to be default ...
- ES6(模板字符串,三点运算符,Symbol,iterator接口)
模板字符串 作用:简化字符串的拼接 模板字符串必须用``包含 变化的部分使用${xxx}包含 对象的简写方式 同名的属性可以省略不写 可以省略函数的function 箭头函数 箭头函数的特点 箭头函数 ...