层次遍历,计算每一层的节点值,然后求平均值。

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的更多相关文章

  1. [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 ...

  2. Leetcode637.Average of Levels in Binary Tree二叉树的层平均值

    给定一个非空二叉树, 返回一个由每层节点平均值组成的数组. class Solution { public: vector<double> averageOfLevels(TreeNode ...

  3. LeetCode637. 二叉树的层平均值

    题目 1 class Solution { 2 public: 3 vector<double>ans; 4 vector<double> averageOfLevels(Tr ...

  4. LeetCode 637. 二叉树的层平均值(Average of Levels in Binary Tree)

    637. 二叉树的层平均值 637. Average of Levels in Binary Tree LeetCode637. Average of Levels in Binary Tree 题目 ...

  5. LeetCode通关:连刷三十九道二叉树,刷疯了!

    分门别类刷算法,坚持,进步! 刷题路线参考:https://github.com/youngyangyang04/leetcode-master 大家好,我是拿输出博客来督促自己刷题的老三,这一节我们 ...

随机推荐

  1. 0.00-050613_zc

    1. ROM bios --> 启动盘第一个扇区(此处内容为boot) 加载到 内存位置0x7C00(31KB) --> 执行权转移(也就相当于跳转) boot程序主要功能:把 软盘/映像 ...

  2. cell 配置

    Cells Cell configuration options Configure the API (top-level) cell Configure the child cells Config ...

  3. UML类图(二)----------类与类之间的关系之关联(聚合与组合)

    类与类之间的关系: 在软件系统中,类并不是孤立存在的,类与类之间存在各种关系,对于不同类型的关系,UML提供了不同的表示方式.       1. 关联关系 关联(Association)关系是类与类之 ...

  4. web自动化:元素定位(二)

    一. 实例 如何定位到下图第二个"抢投标",有一种方法是利用xpath定位 //a[@href="/loan/loan_detail/Id/7190.html" ...

  5. ADO.NET异步操作测试

    配置文件: <?xml version="1.0"?> <configuration> <startup> <supportedRunti ...

  6. Highcharts中更新series的5种方法

    用Highcharts画图时,经常需要更新所画的图表,最常见的就是改变数据以更新图表.在Highcarts中,数据对应的参数是series.这儿就以图1的柱状图为例,列举如何更新series的5种方法 ...

  7. 【Cordova】Cordova开发

    引言 微软开启新战略--移动为先,云为先.作为开发者,首先感受到的变化就是VS2015预览版增加了对各种跨平台框架的支持,极大方便了我们的开发.其中号称原生性能的Xamarin要收费,挺贵的,一般人还 ...

  8. (转)android头像设置:从本地照片库或拍照获取并剪裁

    本文转载于:http://blog.csdn.net/sheeprunning/article/details/9184021 功能介绍 制作android应用时,用户注册的功能必不可少,往往还需要具 ...

  9. Spring_总结_04_高级配置(二)_条件注解@Conditional

    一.前言 本文承接上一节:Spring_总结_04_高级配置(一)之Profile 在上一节,我们了解到 Profile 为不同环境下使用不同的配置提供了支持,那么Profile到底是如何实现的呢?其 ...

  10. datatable绑定comboBox,在下拉菜单中显示对应数据

    实现功能: datatable绑定comboBox,在下拉菜单中显示对应数据 实现方法: .生成datatable,并为combox绑定数据源: comboBox1.DataSource = dt1; ...