-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathzigzag-level-sum-of-binary-tree.cpp
More file actions
34 lines (33 loc) · 1.01 KB
/
zigzag-level-sum-of-binary-tree.cpp
File metadata and controls
34 lines (33 loc) · 1.01 KB
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
// Time: O(n)
// Space: O(w)
// bfs
class Solution {
public:
vector<long long> zigzagLevelSum(TreeNode* root) {
vector<long long> result;
vector<TreeNode *> q = {root};
for (int parity = 0; !empty(q); parity ^= 1) {
vector<TreeNode *> new_q;
int64_t total = 0;
bool stop = false;
for (int i = size(q) - 1; i >= 0; --i) {
const auto& node = q[i];
const auto& left = (parity == 0) ? node->left : node->right;
const auto& right = (parity == 0) ? node->right : node->left;
if (left) {
new_q.emplace_back(left);
}
if (right) {
new_q.emplace_back(right);
}
stop = stop || !left;
if (!stop) {
total += node->val;
}
}
result.emplace_back(total);
q = move(new_q);
}
return result;
}
};