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].
Note:
1. The range of node's value is in the range of 32-bit signed integer.
来自 <https://leetcode.com/problems/average-of-levels-in-binary-tree/description/>
2.题目分析
求二叉树每一层的平均数,并存入到数组中,遍历方法使用层序遍历,关键是怎么判断一层结束了,区别于层序遍历的单队列,这里使用了两个队列,一个存储父节点层,另一个存储子节点层,再父节点层遍历完成后,计算均值并存储,然后交换这两个队列,使得当前子节点层成为下一次计算的父节点层。结束的条件是两个队列都空了。需要注意的是,当父结点层存在,子结点层不存在,即最后一层时,并没有计算最后一层均值,因此需要在循环结束时,计算最后一层均值并存储。
3.C++代码
//我的代码:(beats 42%)
vector<double> averageOfLevels(TreeNode* p)
{
vector<double>r;
queue<TreeNode*>q_root;
queue<TreeNode*>q_child;
q_root.push(p);
int cnt = 0;
double sum = 0;
double aver = 0;
while (!q_root.empty() || !q_child.empty())
{
if (!q_root.empty())
{
TreeNode *tmp = q_root.front();
q_root.pop();
if (tmp->left != NULL)
q_child.push(tmp->left);
if (tmp->right != NULL)
q_child.push(tmp->right);
cnt++;
sum += tmp->val;
}
else
{
aver = sum / cnt;
cnt = 0;
sum = 0;
q_root.swap(q_child);
r.push_back(aver);
}
}
aver = sum / cnt;
r.push_back(aver);
return r;
}
//改进版:(beats 74%)
//只用一个队列,每次大循环处理一行,而不是只处理一个结点
//利用每一层的结点个数就是队列的长度这一特点,减少一个队列
vector<double> averageOfLevels2(TreeNode* p)
{
vector<double>r;
queue<TreeNode*>q;
q.push(p);
int n = 0;
double sum = 0;
double aver = 0;
while (!q.empty())
{
n = q.size();
sum = 0;
for (int i = 0; i < n; i++)
{
TreeNode*tmp = q.front();
q.pop();
sum += tmp->val;
if (tmp->left)
q.push(tmp->left);
if (tmp->right)
q.push(tmp->right);
}
aver = sum / n;
r.push_back(aver);
}
return r;
}