LeetCode637二叉树的层平均值

题目链接

https://leetcode-cn.com/problems/average-of-levels-in-binary-tree/

题解

思路和层次遍历(点击查看)一样,没什么区别。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
// 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/

欢迎讨论和交流!