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

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. Intel Code Challenge Elimination Round (Div.1 + Div.2, combined) C. Destroying Array

    C. Destroying Array time limit per test 1 second memory limit per test 256 megabytes input standard ...

  2. javascript的宿主环境

    关于javascript语言,最有意思的是它必须要在一个宿主环境中运行,其中受欢迎的宿主环境当然就是浏览器了,但这并不是我们唯一的选择, javascript完全可以运行在服务器端,桌面以及富媒体环境 ...

  3. Overlay网络与物理网络的关系

    编者按:无论是云计算还是SDN都把注意力集中在数据中心网络的建设上,各种解决方案层出不穷,其中以VMware为代表的软件厂商提出Overlay网络方案后,为数据中心网络的发展提出了新的思路.那么Ove ...

  4. 直方图均衡化的 C++ 实现(基于 openCV)

    这是数字图像处理课的大作业,完成于 2013/06/17,需要调用 openCV 库,完整源码和报告如下: #include <cv.h> #include <highgui.h&g ...

  5. pythoncook 随记

    第一章 数据结构与算法 1 赋值多个变量 *2 collections deque 构造固定大小队列,插入删除比list快3 查找最大和最小元素的N个元素 heapq nlargest() nsmal ...

  6. Node.js模块、包的学习笔记

    什么是模块 模块是node应用程序的基本组成部分,文件和模块是一一对应的,就是说,一个node文件就是一个模块,这个文件可能是javascript代码.json或者是编译过的c++扩展等,如: var ...

  7. IDEA 上传更新的代码到码云上

    1.Commit Changes 2. .

  8. cassandra 集群并发测试脚本

    prepare: create keyspace ycsb WITH REPLICATION = { }; USE ycsb; CREATE TABLE users ( firstname text, ...

  9. fabric 安装及简单使用 (centos6)

    fabric 是一个python的库,fabric可以通过ssh批量管理服务器. 第一步安装依赖包 安装epel源 1 wget -O /etc/yum.repos.d/epel.repo http: ...

  10. oralce 索引(1)

    本文来自网上整理 来自以下博客内容 http://www.360doc.com/content/13/0712/11/13136648_299364992.shtml; http://www.cnbl ...