Average of Levels in Binary Tree
题目
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.
解析
题目需要我们做的是求二叉树每层的平均数,这就需要我们用到层次遍历,一层一层遍历二叉树,得到每层相应节点的值,计算其平均值。
这样我们可以利用STL中的queue“先进先出”的特点,实现对二叉树的层次遍历,从而可以计算每层节点的平均数。
解决
/**
* 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;
if (root == NULL) return result;
queue<TreeNode *> tree;
tree.push(root);
// 判断是否完成层次遍历
while (!tree.empty()) {
int s = tree.size(); // 记录该层节点个数
double sum = 0;
for (int i = 0; i < s; i++) {
// 遍历该层的所有节点
TreeNode * temp = tree.front();
tree.pop();
// 计算该层节点值的总和
sum += temp->val;
// 为遍历下一层节点做准备
if (temp->left != NULL) {
tree.push(temp->left);
}
if (temp->right != NULL) {
tree.push(temp->right);
}
}
// 记录该层节点的平均值
result.push_back(sum / s);
}
return result;
}
};