LeetCode637二叉树的层平均值
题目链接
https://leetcode-cn.com/problems/average-of-levels-in-binary-tree/
题解
思路和层次遍历(点击查看)一样,没什么区别。
// Problem: LeetCode 637
// URL: https://leetcode-cn.com/problems/average-of-levels-in-binary-tree/
// Tags: Tree Queue
// Difficulty: Easy
#include <iostream>
#include <queue>
#include <vector>
using namespace std;
struct TreeNode{
int val;
TreeNode* left;
TreeNode* right;
};
class Solution{
private:
vector<double> result;
double calcAverageOfLevel(vector<double>& vec){
double sum = 0;
for (vector<double>::iterator it = vec.begin(); it!=vec.end(); ++it) sum += *it;
return sum / vec.size();
}
public:
vector<double> averageOfLevels(TreeNode* root) {
// 空树,返回空数组
if (root==nullptr)
return this->result;
// 父层结点,即当前正在遍历的结点
queue<TreeNode*> parentNodes;
parentNodes.push(root);
// 遍历父层结点的同时获取下一层(子层)结点
while (!parentNodes.empty()){
// 子层结点,即下一层结点
queue<TreeNode*> childNodes;
// 当前层的结点的值
vector<double> valOfLevel;
// 遍历当前层
while (!parentNodes.empty()){
root = parentNodes.front();
parentNodes.pop();
valOfLevel.push_back(root->val);
if (root->left!=nullptr) childNodes.push(root->left);
if (root->right!=nullptr) childNodes.push(root->right);
}
// 计算并存储当前层结点值的平均值
this->result.push_back(this->calcAverageOfLevel(valOfLevel));
// 更新当前层
parentNodes = childNodes;
}
return this->result;
}
};
作者:@臭咸鱼
转载请注明出处:https://www.cnblogs.com/chouxianyu/
欢迎讨论和交流!