原文链接 [每日 LeetCode] 637. Average of Levels in Binary Tree
Description:
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:
- The range of node's value is in the range of 32-bit signed integer.
思路:本题要求二叉树每层结点的平均值,返回此平均值数组。可借助[每日 LeetCode] 102. Binary Tree Level Order Traversal 层序遍历思想,对每层结点入队后进行求平均值操作,最后返回每层结点平均值数组。
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> v;
if(root == NULL)
return v;
queue<TreeNode*> q;
vector<int> a;
q.push(root);
q.push(NULL);
while(!q.empty())
{
TreeNode* temp = q.front();
q.pop();
if(temp==NULL)
{
double sum=0;
for(int i=0;i<a.size();i++)
sum+=a[i];
sum = sum/a.size();
v.push_back(sum);
a.clear();
if(!q.empty())
q.push(NULL);
}
else
{
a.push_back(temp->val);
if(temp->left)
q.push(temp->left);
if(temp->right)
q.push(temp->right);
}
}
return v;
}
};
运行时间:20ms
运行内存:22M
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于