forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcousins-in-binary-tree-ii.cpp
More file actions
28 lines (27 loc) · 890 Bytes
/
Copy pathcousins-in-binary-tree-ii.cpp
File metadata and controls
28 lines (27 loc) · 890 Bytes
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
// Time: O(n)
// Space: O(w)
// bfs
class Solution {
public:
TreeNode* replaceValueInTree(TreeNode* root) {
vector<pair<TreeNode *, int>> q = {{root, root->val}};
while (!empty(q)) {
vector<pair<TreeNode *, int>> new_q;
const int total = accumulate(cbegin(q), cend(q), 0, [](const auto& total, const auto& x) {
return total + x.first->val;
});
for (auto [node, x] : q) {
node->val = total - x;
x = (node->left ? node->left->val : 0) + (node->right ? node->right->val : 0);
if (node->left) {
new_q.emplace_back(node->left, x);
}
if (node->right) {
new_q.emplace_back(node->right, x);
}
}
q = move(new_q);
}
return root;
}
};