leetcode637
层次遍历,计算每一层的节点值,然后求平均值。
class Solution {
public:
vector<double> averageOfLevels(TreeNode* root) {
vector<double> D;
if (root != NULL)
{
queue<TreeNode> Q;
TreeNode node = TreeNode(root->val);
node.left = root->left;
node.right = root->right;
Q.push(node);
while (!Q.empty())
{
//出队列
vector<double> L;
vector<TreeNode> T;
L.clear();
double sum = 0.0;
while (!Q.empty())
{
TreeNode livenode = Q.front();
Q.pop();
L.push_back(livenode.val);
T.push_back(livenode);
}
//计算L中的数值
for (auto v : L)
{
sum += v;
}
sum = sum / L.size();
D.push_back(sum);
//将左右子树放入队列
for (auto t : T)
{
if (t.left != NULL)
{
Q.push(*t.left);
}
if (t.right != NULL)
{
Q.push(*t.right);
}
}
}
}
return D;
}
};
leetcode637的更多相关文章
- [Swift]LeetCode637. 二叉树的层平均值 | 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 ...
- LeetCode637. 二叉树的层平均值
题目 1 class Solution { 2 public: 3 vector<double>ans; 4 vector<double> averageOfLevels(Tr ...
- LeetCode 637. 二叉树的层平均值(Average of Levels in Binary Tree)
637. 二叉树的层平均值 637. Average of Levels in Binary Tree LeetCode637. Average of Levels in Binary Tree 题目 ...
- LeetCode通关:连刷三十九道二叉树,刷疯了!
分门别类刷算法,坚持,进步! 刷题路线参考:https://github.com/youngyangyang04/leetcode-master 大家好,我是拿输出博客来督促自己刷题的老三,这一节我们 ...
随机推荐
- 汇编笔记 RET
assume cs:code,ss:stack stack segment db dup() stack ends code segment mov ax,4c00h int 21h start: m ...
- 添加vue调试工具vue-devtolls
1.在使用脚手架vue-cli.js下载好node-modules 2.在node-modules目录下找的vue-devtools文件(如果没有可以用npm install vue-devtools ...
- poj 2478 Farey Sequence 欧拉函数前缀和
Farey Sequence Time Limit: 1000MS Memory Limit: 65536K Description The Farey Sequence Fn for ...
- ControlTemplate,ItemsPanelTemplate,DataTemplate(wpf)
在WPF中有三大模板ControlTemplate,ItemsPanelTemplate,DataTemplate.其中ControlTemplate和ItemsPanelTemplate是控件模板, ...
- mpv 播放器
https://mpv.io/ Mac版本: 官网: https://mpv.io/ https://mpv.io/installation/ 下载: http://sva.wakku.to/~chr ...
- hdu 1848 Fibonacci again and again(sg)
Fibonacci again and again Time Limit: 1000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Jav ...
- android横屏布局文件设置
一.AndroidManifest.xml配置 1.在AndroidManifest.xml的activity(需要禁止转向的activity)配置中加入 android:screenOrient ...
- 设置cookie的保存时间 下一篇
设置cookie的保存时间,通过cookie的expires性质指定一个终止时间就可以了.也就是说,你在设置cookie的时候,你的cookie字串要像下面这样组合: var d= new Date( ...
- 【暂时解决】win10下安装VS2017 15.3版本 提示 未能安装包“Microsoft.NET.4.6.FullRedist.NonThreshold.Resources,version=4.6.81.9,language=zh-CN”。
win10下安装VS2017 15.3版本的时候,出现以上错误日志提示,请问如何解决的哇? 这个问题,开始我以为是我的安装包所在的路径问题引起的,但是我将安装包移动到了磁盘根目录进行安装,依然出现这个 ...
- Redis 高可用及分片集群,说了你也不懂
Redis 简介 Memcached: 优点:高性能读写.单一数据类型.支持客户端式分布式集群.一致性hash 多核结构.多线程读写性能高. 缺点:无持久化.节点故障可能出现缓存穿透.分布式需要客户端 ...