637. Average of Levels in Binary Tree
来源:互联网 发布:百度程序员待遇 编辑:程序博客网 时间:2024/04/29 18:33
题目描述:
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 7Output: [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:
- The range of node's value is in the range of 32-bit signed integer.
利用层次遍历,重点在于分层,分出层之后就能求出每一层的平均值了。时间复杂度O(n)
答案详解:
/**
* 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> a;
TreeNode* p = root;
int rear = -1;//生命队列的前后位置
int front = -1;
int last = 0;//当front等于last时,level++
int level = 0;
struct TreeNode* q[10001];//将节点存在队列里面
double ave;//每层的平均数
int i = 0;//每一层有几个节点
if(root=NULL){
a.push_back(NULL);
return a;
}
q[++rear] = p;//初始化第一个节点
i=0;
while(front<rear)
{
ave = ave + q[++front]->val;
cout<< ave << endl;
p = q[front];
i++;
if(p->left){
q[++rear] = p->left;
}
if(p->right){
q[++rear] = p->right;
}
if( front == last)
{
a.push_back(ave/i);
last = rear;
ave = 0;
i=0;
}
}
return a;
}
};
阅读全文
0 0
- 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
- 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
- 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
- 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
- 637. Average of Levels in Binary Tree
- [Leetcode] Binary tree-- 637. Average of Levels in Binary Tree
- 计算机图形学-直线的生成算法
- [Excel图表]用excel画坐标散点图,并添加数据标签
- C#回顾学习笔记三十九:事务
- 文章标题
- 最近好累
- 637. Average of Levels in Binary Tree
- 【数据结构】【C++STL】动态数组 集合 映射和优先队列
- eclipse之project facets
- 小白入门---Vue无限滚动(vue-infinite-scroll)
- Android基础面试简答题
- iOS-百度语音识别
- Tensorflowonspark standalone安装
- python3基础知识一
- [Thinking in Java]