LeetCode 637. 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].
按照题目要求求解二叉树每层的平均值,既然按照层级求解,那么可以说是层次遍历或者说是BFS的典型问题。
关键在于如何正确的在遍历过程中分层,思路是根据压入队列的元素个数划分。代码如下:
/**
* 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;
q.push(root);
while (!q.empty())
{
int num = q.size();
long temp = 0;
for (int i = 0; i < num; i++)
{
TreeNode *top = q.front();
q.pop();
if (top->left != NULL)
q.push(top->left);
if (top->right != NULL)
q.push(top->right);
temp += top->val;
}
v.push_back((double)temp / num);
}
return v;
}
};版权声明:本文为qwas12345qwas原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。