0979.cpp (689B)
1 class Solution { 2 public: 3 int distributeCoins(TreeNode *root) { 4 TreeNode dummy(0); 5 stack<pair<TreeNode *, TreeNode *>> q({{root, &dummy}}); 6 7 int res = 0; 8 while (!q.empty()) { 9 auto [root, parent] = q.top(); 10 if (root) { 11 q.push({nullptr, nullptr}); 12 if (root->left) q.push({root->left, root}); 13 if (root->right) q.push({root->right, root}); 14 continue; 15 } 16 q.pop(); 17 tie(root, parent) = q.top(); 18 q.pop(); 19 parent->val += root->val - 1; 20 res += abs(root->val - 1); 21 } 22 23 return res; 24 } 25 };