Skip to content

Commit e469905

Browse files
authored
Create cousins-in-binary-tree-ii.cpp
1 parent 8bcb8de commit e469905

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

C++/cousins-in-binary-tree-ii.cpp

+28
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
// Time: O(n)
2+
// Space: O(w)
3+
4+
// bfs
5+
class Solution {
6+
public:
7+
TreeNode* replaceValueInTree(TreeNode* root) {
8+
vector<pair<TreeNode *, int>> q = {{root, root->val}};
9+
while (!empty(q)) {
10+
vector<pair<TreeNode *, int>> new_q;
11+
const int total = accumulate(cbegin(q), cend(q), 0, [](const auto& total, const auto& x) {
12+
return total + x.first->val;
13+
});
14+
for (auto [node, x] : q) {
15+
node->val = total - x;
16+
x = (node->left ? node->left->val : 0) + (node->right ? node->right->val : 0);
17+
if (node->left) {
18+
new_q.emplace_back(node->left, x);
19+
}
20+
if (node->right) {
21+
new_q.emplace_back(node->right, x);
22+
}
23+
}
24+
q = move(new_q);
25+
}
26+
return root;
27+
}
28+
};

0 commit comments

Comments
 (0)