We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
2 parents 9593e07 + c140cc8 commit 7298e0aCopy full SHA for 7298e0a
2641. Cousins in Binary Tree II
@@ -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