Skip to content

Commit

Permalink
week50
Browse files Browse the repository at this point in the history
  • Loading branch information
조우석[Naver Game Server Dev] committed Apr 15, 2024
1 parent 97b488d commit e4d8fc8
Showing 1 changed file with 36 additions and 0 deletions.
36 changes: 36 additions & 0 deletions 우석/leetcode/average-of-levels-in-binary-tree.cc
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<double> averageOfLevels(TreeNode* root) {
vector<double> result;
vector<int> count;
average(root, 0, result, count);
for (int i = 0; i < result.size(); i++) {
result[i] /= count[i];
}
return result;
}

void average(TreeNode* node, int level, vector<double> &sum, vector<int> &count) {
if (node == nullptr) return;
if (level < sum.size()) {
sum[level] += node->val;
count[level] += 1;
} else {
sum.push_back(node->val);
count.push_back(1);
}
average(node->left, level + 1, sum, count);
average(node->right, level + 1, sum, count);
}
};

0 comments on commit e4d8fc8

Please sign in to comment.