979. Distribute Coins in Binary Tree




Last updated




Last updated
Input: [3,0,0]
Output: 2
Explanation: From the root of the tree, we move one coin to its left child, and one coin to its right child.Input: [0,3,0]
Output: 3
Explanation: From the left child of the root, we move two coins to the root [taking two moves]. Then, we move one coin from the root of the tree to the right child.Input: [1,0,2]
Output: 2Input: [1,0,0,null,3]
Output: 4int helper(TreeNode* root, int& res) {
if (!root) return 0;
int left = helper(root->left, res), right = helper(root->right, res);
res += abs(left) + abs(right);
return (root->val - 1) + left + right; // minus 1 for keeping one for the current node
}
int distributeCoins(TreeNode* root) { // time: O(n); space: O(h)
int res = 0;
helper(root, res);
return res;
}