[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 ...
随机推荐
- mybatis配置打印sql
mybatis配置打印sql: <settings> <setting name="logImpl" value="STDOUT_LOGGING&quo ...
- PHP隐藏IP地址末位的方法
很久之前写过一个使用ASP隐藏IP地址末位的文章,也就是有时候为了保护用户的隐私,会隐藏用户的IP地址,达成类似于 222.222.222.* 的效果. 现在想要用PHP来实现,经过尝试,其实非常简 ...
- nginx1.15.10配置使用非https访问返回403
nginx版本号:nginx version: nginx/1.15.10 server { listen 443 default ssl; server_name app.test.com; if ...
- httpclient post请求中文乱码解决办法
在使用httpclient发送post请求的时候,接收端中文乱码问题解决. 正文: 我们都知道,一般情况下使用post请求是不会出现中文乱码的.可是在使用httpclient发送post请求报文含中文 ...
- c#语言学习笔记(1)
环境:VS Express 2013 for Desktop 也可以vs社区版,不过学习的话,Express本版做一些小的上位机工具应该是够用了 学习的网站:https://www.runoob.co ...
- DataGridView 导出Excel (封装)
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.W ...
- react基本语法及组件
一.react简介 1.起源:React 起源于 Facebook 的内部项目,用来架设 Instagram 的网站,并于 2013 年 5 月开源. 2.特点: 1.声明式设计 −React采用声明 ...
- php解决大文件断点续传
核心原理: 该项目核心就是文件分块上传.前后端要高度配合,需要双方约定好一些数据,才能完成大文件分块,我们在项目中要重点解决的以下问题. * 如何分片: * 如何合成一个文件: * 中断了从哪个分片开 ...
- 非旋转 treap
其实之前学过一次非旋转 treap,但是全忘光了,今天复习一下. 洛谷 P3369 [模板]普通平衡树 code: #include <bits/stdc++.h> #define N 1 ...
- node安装失败报错
安装Node有时会报错 提示这段信息 怎么安装都不行 最后通过命令行安装就可以完成 1.首先去Node下载安装包 下载完后放在本地 比如我放在桌面aa这个文件夹里 2.进去aa这个文件 复制里面的路 ...