Leetcode 637. Average of Levels in Binary Tree
阿新 • • 發佈:2018-12-11
文章作者:Tyan 部落格:noahsnail.com | CSDN | 簡書
1. Description
2. Solution
- Version 1
/**
* 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) {
}
queue<TreeNode*> q;
q.push(root);
q.push(nullptr);
double sum = 0;
int count = 0;
while(!q.empty()) {
TreeNode* current = q.front();
q.pop();
if(current) {
count++;
sum += current->val;
if(current->left) {
q.push(current->left);
}
if(current->right) {
q.push (current->right);
}
}
else if(count){
double mean = sum / count;
sum = 0;
count = 0;
result.push_back(mean);
q.push(nullptr);
}
}
return result;
}
};
- Version 2
/**
* 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) {
return result;
}
queue<TreeNode*> q;
q.push(root);
double sum = 0;
while(!q.empty()) {
sum = 0;
int size = q.size();
for(int i = 0; i < size; i++) {
TreeNode* current = q.front();
q.pop();
sum += current->val;
if(current->left) {
q.push(current->left);
}
if(current->right) {
q.push(current->right);
}
}
result.push_back(sum / size);
}
return result;
}
};