From c140cc8ca29b2e099c4aa07d4e3901d6f7b581a7 Mon Sep 17 00:00:00 2001 From: chayan das <110921638+Chayandas07@users.noreply.github.com> Date: Thu, 24 Oct 2024 00:03:25 +0530 Subject: [PATCH] Create 2641. Cousins in Binary Tree II --- 2641. Cousins in Binary Tree II | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 2641. Cousins in Binary Tree II diff --git a/2641. Cousins in Binary Tree II b/2641. Cousins in Binary Tree II new file mode 100644 index 0000000..55bf651 --- /dev/null +++ b/2641. Cousins in Binary Tree II @@ -0,0 +1,30 @@ +class Solution { +public: + TreeNode* replaceValueInTree(TreeNode* root) { + queue> qu; + qu.push({root, 0}); + int prev = 0; + + while(!qu.empty()) { + int n = qu.size(); + int temp = 0; + for(int i = 0; i < n; i++) { + auto [curr, value] = qu.front(); qu.pop(); + + curr -> val = (prev - value); + int siblings = 0; + + if(curr -> right) siblings += curr -> right -> val; + if(curr -> left) { + siblings += curr -> left -> val; + qu.push({curr -> left, siblings}); + } + if(curr -> right) qu.push({curr -> right, siblings}); + + temp += siblings; + } + prev = temp; + } + return root; + } +};