2641.cpp (1032B)
1 class Solution { 2 public: 3 TreeNode *replaceValueInTree(TreeNode *root) { 4 queue<TreeNode *> q({root}); 5 vector<TreeNode *> buf; 6 root->val = 0; 7 while (!q.empty()) { 8 int sum = 0; 9 buf.clear(); 10 for (int k = q.size(); k > 0; k--) { 11 TreeNode *node = q.front(); 12 q.pop(); 13 buf.push_back(node); 14 15 if (node->left) { 16 sum += node->left->val; 17 q.push(node->left); 18 } 19 20 if (node->right) { 21 sum += node->right->val; 22 q.push(node->right); 23 } 24 } 25 for (auto node : buf) { 26 int t = sum; 27 if (node->left) t -= node->left->val; 28 if (node->right) t -= node->right->val; 29 if (node->left) node->left->val = t; 30 if (node->right) node->right->val = t; 31 } 32 } 33 return root; 34 } 35 };