Created
May 1, 2018 14:00
-
-
Save s4553711/94eaf4488fb86078bef69b14395b93ec to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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> ans; | |
if (root == NULL) return ans; | |
queue<TreeNode*> q; | |
q.push(root); | |
while(!q.empty()) { | |
int n = q.size(); | |
long long sum = 0; | |
for(int i = 0; i < n; i++) { | |
TreeNode* t = q.front(); | |
q.pop(); | |
if (t->left) q.push(t->left); | |
if (t->right) q.push(t->right); | |
sum += t->val; | |
} | |
ans.push_back(static_cast<double>(sum) / n); | |
} | |
return ans; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment