-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy path2641.cpp
More file actions
35 lines (33 loc) · 1.01 KB
/
Copy path2641.cpp
File metadata and controls
35 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
35
class Solution {
public:
TreeNode *replaceValueInTree(TreeNode *root) {
queue<TreeNode *> q({root});
vector<TreeNode *> buf;
root->val = 0;
while (!q.empty()) {
int sum = 0;
buf.clear();
for (int k = q.size(); k > 0; k--) {
TreeNode *node = q.front();
q.pop();
buf.push_back(node);
if (node->left) {
sum += node->left->val;
q.push(node->left);
}
if (node->right) {
sum += node->right->val;
q.push(node->right);
}
}
for (auto node : buf) {
int t = sum;
if (node->left) t -= node->left->val;
if (node->right) t -= node->right->val;
if (node->left) node->left->val = t;
if (node->right) node->right->val = t;
}
}
return root;
}
};