leetcode 637. Average of Levels in Binary Tree
来源:互联网 发布:java 读取apk版本号 编辑:程序博客网 时间:2024/06/14 07:58
1.题目
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].
注意每个节点上的值为32位有符号整数
Note:
The range of node’s value is in the range of 32-bit signed integer.
2.分析
广度优先遍历,对每一层的节点值求和,再取平均值。
注意:由于节点值32位整数,求和如果用int保存会溢出,而平均值是double类型。所以用double来保存求和
3.代码
vector<double> averageOfLevels(TreeNode* root) { queue<TreeNode*> nodes; nodes.push(root); vector<double> ans; while (!nodes.empty()) { int n = nodes.size(); int sum = 0; for (int i = 0; i < n; i++) { TreeNode* node = nodes.front(); sum += node->val; nodes.pop(); if(node->left) nodes.push(node->left); if(node->right) nodes.push(node->right); } ans.push_back((double)sum / n); } return ans;}
阅读全文
0 0
- [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
- LeetCode 637. Average of Levels in Binary Tree
- [LeetCode] 637.Average of Levels in Binary Tree
- 637. Average of Levels in Binary Tree
- 637. Average of Levels in Binary Tree
- 637. Average of Levels in Binary Tree
- <c:forEach>详解
- 微信公众号中信息推送出现中文乱码的问题的思考
- android开发中常见的问题
- 【Redis源码剖析】
- Week5 Lasso Regression
- leetcode 637. Average of Levels in Binary Tree
- Spring (三)注入依赖对象、注入集合类型的属性
- 用户特征分析的应用
- [日推荐]『智能小蜜』专治各种无聊
- js关闭浏览器前弹窗
- 复选框checkbox如何判定为被选中
- 【c++】面试题:----根据Unix时间戳计算时间
- 运营效果分析的典型应用
- 新手linux 搭建gerrit过程。