leetCode 637. Average of Levels in Binary Tree 求二叉树每层平均值
来源:互联网 发布:python for 一行 编辑:程序博客网 时间:2024/06/06 04:35
题目描述:
Given a non-empty binary tree, return the average value of the nodes on each level in the form of an array.
Example 1:
Input :
3
/ \
9 20
/ \
15 7
Output : [ 3 , 14.5, 11 ]
Explanation :
The average value of nodes on level 0 is 3, on level 1 is 14.5, and on level 2 is 11. Hence return [3, 14.5, 11].
Note:
1.The range of node’s value is in the range of 32-bit signed integer.
解题思路:
求解每层节点的平均值,“层”第一时间应该想到的是层次遍历(level-traverse);遍历每一层的节点求出平均值,并将该层的子节点存入数组。
c++代码:
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public: vector<double> averageOfLevels(TreeNode* root) { vector<double> result; vector<TreeNode *> vec; int lastL = 0; double average = 0; vec.push_back(root); while (lastL != vec.size()) { int times = 0; for (int i = lastL,size = vec.size(); i <size ; ++i,++times){ average += vec[i]->val; if (vec[i]->left) vec.push_back(vec[i]->left); if (vec[i]->right) vec.push_back(vec[i]->right); } result.push_back(average / times); average = 0; lastL += times; } return result; }};
阅读全文
0 0
- leetCode 637. Average of Levels in Binary Tree 求二叉树每层平均值
- leetcode Average of Levels in Binary Tree 二叉树每层的平均值
- 637. Average of Levels in Binary Tree 二叉树每层平均值
- leetcode 637. Average of Levels in Binary Tree二叉树的每层平均数
- 【二叉树】637. Average of Levels in Binary Tree
- [Leetcode] Binary tree-- 637. Average of Levels in Binary Tree
- LeetCode average Of Levels in Binary Tree
- Average of Levels in Binary Tree(leetcode)
- LeetCode 637. Average of Levels in Binary Tree
- [LeetCode]637. Average of Levels in Binary Tree
- leetcode 637. Average of Levels in Binary Tree
- [LeetCode]637. Average of Levels in Binary Tree
- 【LeetCode】637. Average of Levels in Binary Tree
- leetcode 637. Average of Levels in Binary Tree
- leetcode 637. Average of Levels in Binary Tree
- [LeetCode] 637. Average of Levels in Binary Tree
- leetcode 637. Average of Levels in Binary Tree
- <leetcode>637. Average of Levels in Binary Tree
- Flink新一代流式计算框架的体系架构及应用
- 专访 | 余承东:华为三大智能平台先从国内发力
- 京东推游戏手机标准背后 重塑手机产业生产模式
- Java并发编程之原子变量
- AlphaGo Zero 模型框架
- leetCode 637. Average of Levels in Binary Tree 求二叉树每层平均值
- 最大子数组的和以及最大子数组的乘积
- 122. Best Time to Buy and Sell Stock II
- PyCharm使用技巧:Ctrl + /(多行注释)
- 游戏背景音乐
- Android系统prop属性的研究与分析(二)
- CentOS安装邮件服务器
- 关于Android studio使用外来项目,以导入zxing包为例子
- Generative Adversarial Nets