給定一個有 N 個結點的二叉樹的根結點 root,樹中的每個結點上都對應有 node.val 枚硬幣,並且總共有 N 枚硬幣。
在一次移動中,我們可以選擇兩個相鄰的結點,然後將一枚硬幣從其中一個結點移動到另一個結點。(移動可以是從父結點到子結點,或者從子結點移動到父結點。)。
返回使每個結點上只有一枚硬幣所需的移動次數。
示例 1:
輸入:[3,0,0]
輸出:2
解釋:從樹的根結點開始,我們將一枚硬幣移到它的左子結點上,一枚硬幣移到它的右子結點上。
示例 2:
輸入:[0,3,0]
輸出:3
解釋:從根結點的左子結點開始,我們將兩枚硬幣移到根結點上 [移動兩次]。然後,我們把一枚硬幣從根結點移到右子結點上。
示例 3:
輸入:[1,0,2]
輸出:2
示例 4:
輸入:[1,0,0,null,3]
輸出:4
提示:
1<= N <= 100
0 <= node.val <= N
class Solution {
public:
int distributeCoins(TreeNode* root,long &dif) {
if(!root)
{
dif=0;
return 0;
}
long dif1,dif2;
int ans1=distributeCoins(root->left,dif1),ans2=distributeCoins(root->right,dif2);
dif=dif1+dif2+root->val-1;
return ans1+ans2+abs(dif);
}
int distributeCoins(TreeNode* root) {
long dif=0;
return distributeCoins(root,dif);
}
};