[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 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.
给一个非空二叉树,返回每层的平均值组成的数组。
解法:BFS迭代,层序遍历,计算每层的平均值记录到res数组,最后返回res数组。
Java:
public List<Double> averageOfLevels(TreeNode root) {
List<Double> result = new ArrayList<>();
Queue<TreeNode> q = new LinkedList<>();
if(root == null) return result;
q.add(root);
while(!q.isEmpty()) {
int n = q.size();
double sum = 0.0;
for(int i = 0; i < n; i++) {
TreeNode node = q.poll();
sum += node.val;
if(node.left != null) q.offer(node.left);
if(node.right != null) q.offer(node.right);
}
result.add(sum / n);
}
return result;
}
Java: BFS
public List<Double> averageOfLevels(TreeNode root) {
List<Double> list = new LinkedList<>();
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()) {
int count = queue.size();
double sum = 0;
for (int i = 0; i < count; i++) {
TreeNode cur = queue.poll();
sum += cur.val;
if (cur.left != null) queue.offer(cur.left);
if (cur.right != null) queue.offer(cur.right);
}
list.add(sum / count);
}
return list;
}
Java: DFS
class Node {
double sum;
int count;
Node (double d, int c) {
sum = d;
count = c;
}
}
public List<Double> averageOfLevels(TreeNode root) {
List<Node> temp = new ArrayList<>();
helper(root, temp, 0);
List<Double> result = new LinkedList<>();
for (int i = 0; i < temp.size(); i++) {
result.add(temp.get(i).sum / temp.get(i).count);
}
return result;
}
public void helper(TreeNode root, List<Node> temp, int level) {
if (root == null) return;
if (level == temp.size()) {
Node node = new Node((double)root.val, 1);
temp.add(node);
} else {
temp.get(level).sum += root.val;
temp.get(level).count++;
}
helper(root.left, temp, level + 1);
helper(root.right, temp, level + 1);
}
Python:
# Time: O(n)
# Space: O(h)
class Solution(object):
def averageOfLevels(self, root):
"""
:type root: TreeNode
:rtype: List[float]
"""
result = []
q = [root]
while q:
total, count = 0, 0
next_q = []
for n in q:
total += n.val
count += 1
if n.left:
next_q.append(n.left)
if n.right:
next_q.append(n.right)
q = next_q
result.append(float(total) / count)
return result
Python:
class Solution(object):
def averageOfLevels(self, root):
"""
:type root: TreeNode
:rtype: List[float]
"""
if root is None:
return []
result, current = [], [root]
while current:
next_level, vals, = [], 0.0
counts = len(current)
for node in current:
vals += node.val
if node.left:
next_level.append(node.left)
if node.right:
next_level.append(node.right)
current = next_level
result.append(vals / counts) return result
Python: wo
# 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.helper([root], res)
return res def helper(self, q, res):
sm = 0.0
counts = 0
next_level = []
while q:
node = q.pop()
counts += 1
sm += node.val
if node.left:
next_level.append(node.left)
if node.right:
next_level.append(node.right)
res.append(sm / counts)
if next_level:
self.helper(next_level, res)
C++:
class Solution {
public:
vector<double> averageOfLevels(TreeNode* root) {
if (!root) return {};
vector<double> res;
queue<TreeNode*> q{{root}};
while (!q.empty()) {
int n = q.size();
double sum = 0;
for (int i = 0; i < n; ++i) {
TreeNode *t = q.front(); q.pop();
sum += t->val;
if (t->left) q.push(t->left);
if (t->right) q.push(t->right);
}
res.push_back(sum / n);
}
return res;
}
};
C++:
class Solution {
public:
vector<double> averageOfLevels(TreeNode* root) {
vector<double> res, cnt;
helper(root, 0, cnt, res);
for (int i = 0; i < res.size(); ++i) {
res[i] /= cnt[i];
}
return res;
}
void helper(TreeNode* node, int level, vector<double>& cnt, vector<double>& res) {
if (!node) return;
if (res.size() <= level) {
res.push_back(0);
cnt.push_back(0);
}
res[level] += node->val;
++cnt[level];
helper(node->left, level + 1, cnt, res);
helper(node->right, level + 1, cnt, res);
}
};
类似题目:
[LeetCode] 102. Binary Tree Level Order Traversal 二叉树层序遍历
[LeetCode] 107. Binary Tree Level Order Traversal II 二叉树层序遍历 II
[LeetCode] 199. Binary Tree Right Side View 二叉树的右侧视图
All LeetCode Questions List 题目汇总
[LeetCode] 637. Average of Levels in Binary Tree 二叉树的层平均值的更多相关文章
- 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] 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 ...
- Leetcode637.Average of Levels in Binary Tree二叉树的层平均值
给定一个非空二叉树, 返回一个由每层节点平均值组成的数组. class Solution { public: vector<double> averageOfLevels(TreeNode ...
- 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(层序遍历)
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 二叉树的层次遍历再求均值
[抄题]: Given a non-empty binary tree, return the average value of the nodes on each level in the form ...
- 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 ...
随机推荐
- Python 3 新特性:类型注解——类似注释吧,反正解释器又不做校验
Python 3 新特性:类型注解 Crossin 上海交通大学 计算机应用技术硕士 95 人赞同了该文章 前几天有同学问到,这个写法是什么意思: def add(x:int, y:int) - ...
- php的插入排序
感觉在这个数据量上,排入比冒泡要好很多呢~ 代码: <?php /** * 直接插入排序(类比抓牌) * 原理:每次从无序列表中取出第一个元素,把他插入到有序表中的合适位置,使有序表仍然有序 * ...
- ARTS-week3
Algorithm 给定一个排序数组,你需要在原地删除重复出现的元素,使得每个元素只出现一次,返回移除后数组的新长度.不要使用额外的数组空间,你必须在原地修改输入数组并在使用 O(1) 额外空间的条件 ...
- linux中的alias命令详解
功能说明:设置指令的别名.语 法:alias[别名]=[指令名称]参 数 :若不加任何参数,则列出目前所有的别名设置.举 例 :ermao@lost-desktop:~$ alias ...
- BZOJ 2006: [NOI2010]超级钢琴 ST表+堆
开始想到了一个二分+主席树的 $O(n\log^2 n)$ 的做法. 能过,但是太无脑了. 看了一下题解,有一个 ST 表+堆的优美解法. 你发现肯定是选取前 k 大最优. 然后第一次选的话直接选固定 ...
- pyqt5 + pyinstaller 制作爬虫小程序
环境:mac python3.7 pyqt5 pyinstaller ps: 主要是熟悉pyqt5, 加入了单选框 输入框 文本框 文件夹选择框及日历下拉框 效果图: pyqt5 主程序文件 # -* ...
- rollup node.js 打包工具
最近在做一个提供给浏览器和node同时使用的js的url模板工具类,在用什么打包工具上纠结了一段时间,正好有一天在知乎上看到了关于rollup的介绍,在自己试了试之后,就决定用rollup.js来打包 ...
- 改变Ubuntu命令行 用户名显示前缀
改变Ubuntu命令行 用户名显示前缀 1.修改命令 [root@daokr ubuntu]#vim ~/.bashrc 修改第 56行 注释掉原来 # PS1='${debian_chroot:+( ...
- 【JOISC2018|2019】【20190622】mergers
题目 一\(n\)个节点的树,节点被分成\(k\)个集合,\(i\)属于\(S_i\), 一条边是可划分的当且仅当左右两边的子树不存在相同集合的点 你一次可以合并两个集合,求最少的操作次数使得所有边都 ...
- linux命令之------Tar解压缩
Tar解压缩 作用:将解压缩后缀名为tar的压缩包 -f<备份文件>或—file=<备份文件>指定备份文件 -v或-verbose显示指令执行过程 -x或-extract或-g ...