LeetCode637 Average of Levels in Binary Tree


题目

LeetCode637 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
/**
* 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) {
queue<TreeNode*> que;
que.push(root); que.push(nullptr);
double sum = 0, cnt = 0;
vector<double> ret;
while (!que.empty()) {
TreeNode* u = que.front(); que.pop();
if (u == nullptr) {
ret.push_back(sum / cnt);
sum = cnt = 0;
if (!que.empty()) que.push(nullptr);
} else {
sum += u->val; cnt++;
if (u->left) que.push(u->left);
if (u->right) que.push(u->right);
}
}
return ret;
}
};