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

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. YII2笔记之三

    activeform布局findAll等不能满足where, order by, limit,底层调用了findByConditioncol-md col-lg的使用 view的方法,前三个常用ren ...

  2. Compaction介绍

    Compaction介绍 Compaction是buffer->flush->merge的Log-Structured Merge-Tree模型的关键操作,主要起到如下几个作用: 1)合并 ...

  3. 第一个Python程序hello.py提示出现File "<stdin>",line 1错误

    写第一个Python程序hello.py,内容仅有一句,print 'hello world', 运行 Python hello.py 出错,提示: File "<stdin>& ...

  4. 《Advanced Bash-scripting Guide》学习(十九):两个整数的最大公约数

    本文所选的例子来自于<Advanced Bash-scripting Gudie>一书,译者 杨春敏 黄毅 #!/bin/bash #求两个整数的最大公约数 E_BADARGS= #如果参 ...

  5. java常用封装方法

    public Map<String,String> getDateByStr(String str,String startDate,String endTime){ Map<Str ...

  6. hdu 1517 A Multiplication Game(必胜态,必败态)

    A Multiplication Game Time Limit: 5000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Ot ...

  7. ItelliJ IDEA下载及获取注册码详解

    Idea安装很简单: 官网地址下载:https://www.jetbrains.com/idea/ 注册码获取:http://idea.lanyus.com/   进入此网址,点击“获得注册码”复制使 ...

  8. vue配置stylus

    首先Vue-init webapck 随便一个name vue项目创建好之后 cnpm i  (利用淘宝镜像) cnpm i stylus stylus-loader -D 进行安装和配置 styl常 ...

  9. 面试题41:和为s的两个数字VS和为s的连续正数序列

    题目一:输入一个递增排序的数组和一个数字s,在数组中查找两个数,使得它们的和正好是s.如果有多对数字的和为s,输出任意一对即可. vector<int> findNumberwWithSu ...

  10. Unity3D 自动寻路入门指南

    所有用于成为NavMesh的网格都必须被指定为 Navigation Static . 方法如下,选中GameObject,然后在菜单栏的[Window]-[Navigation]-[Object]- ...