- Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsolution.cpp
40 lines (39 loc) · 1.09 KB
/
solution.cpp
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
// level-order traversal
/**
* 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) {}
* };
*/
classSolution {
public:
intmaxLevelSum(TreeNode* root) {
queue<TreeNode *> q{{root}};
int ans = INT_MIN, ans_idx = -1, idx = 1;
while(!q.empty()) {
int sz = q.size();
vector<int> tmp;
while(sz--) {
auto t = q.front();
q.pop();
tmp.push_back(t->val);
if(t->left)
q.push(t->left);
if(t->right)
q.push(t->right);
}
int sum = std::accumulate(begin(tmp), end(tmp), 0);
if(ans < sum) {
ans = sum;
ans_idx = idx;
}
idx++;
}
return ans_idx;
}
};