Skip to content

Commit 7298e0a

Browse files
authored
Create 2641. Cousins in Binary Tree II (#616)
2 parents 9593e07 + c140cc8 commit 7298e0a

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

2641. Cousins in Binary Tree II

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
class Solution {
2+
public:
3+
TreeNode* replaceValueInTree(TreeNode* root) {
4+
queue<pair<TreeNode*, int>> qu;
5+
qu.push({root, 0});
6+
int prev = 0;
7+
8+
while(!qu.empty()) {
9+
int n = qu.size();
10+
int temp = 0;
11+
for(int i = 0; i < n; i++) {
12+
auto [curr, value] = qu.front(); qu.pop();
13+
14+
curr -> val = (prev - value);
15+
int siblings = 0;
16+
17+
if(curr -> right) siblings += curr -> right -> val;
18+
if(curr -> left) {
19+
siblings += curr -> left -> val;
20+
qu.push({curr -> left, siblings});
21+
}
22+
if(curr -> right) qu.push({curr -> right, siblings});
23+
24+
temp += siblings;
25+
}
26+
prev = temp;
27+
}
28+
return root;
29+
}
30+
};

0 commit comments

Comments
 (0)