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

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. HTTP 指纹识别v0.1

    // Winhttp.cpp : 定义控制台应用程序的入口点. // #include "stdafx.h" #include <Windows.h> #include ...

  2. Linux嵌入式 -- Bootloader , Uboot

    1. Bootloader作用 PC机中的引导加载程序由BIOS(其本质是一段固件程序)和GRUB或LILO一起组成.BIOS在完成硬件检测和资源分配后,将硬盘中的引导程序读到系统内存中然后将控制权交 ...

  3. 用TinyXml做XML解析示例 TinyXml查找唯一节点及修改节点操作

    // 读者对象:对TinyXml有一定了解的人.本文是对TinyXml工具的一些知识点的理解. // 1 TinyXml中对TiXmlNode进行了分类,是用一个枚举进行描述的. // enum No ...

  4. 用SQL语句删除除了id不同,其他都相同的学生表信息

    delete from <table_name> wehere id not in (select max(id) from <table_name> group by < ...

  5. 语音01_TTS

    1.http://blog.csdn.net/u010176014/article/details/47428595 2.家里 Win7x64 安装“微软TTS5.1语音引擎(中文).msi”之后,搜 ...

  6. css页面缩放

    如果原来的宽度是1200, 缩放之后宽度可能就变成了1560, 然后你本来的图片1200可能就开始显示不全了. 如果你的图片按100%显示的话,这个时候又正常了.

  7. java中如何将string 转化成long

    1.Java中如何将string 转化成long long l = Long.parseLong([String]); 或 long l = Long.parseLong([String],[int ...

  8. Element 'beans' cannot have character [children], because the type's content type is element-only

    这个小问题快搞死我了,找了大半个小时. Element 'beans' cannot have character [children], because the type's content typ ...

  9. InputStream与String,Byte之间互转

    import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOExceptio ...

  10. controller返回js中文变成?解决方案

    在使用spring-mvc的mvc的时候既享受它带来的便捷,又头痛它的一些问题,比如经典的中文乱码问题.现在是用json作为客户端和服务端 的数据交换格式貌似很流行,但是在springmvc中有时候会 ...