classSolution{public:intdistributeCoins(TreeNode*root){intans=0;dfs(root,ans);returnans;}// Returns how many coins I can give (positive) / take (negative)private:intdfs(TreeNode*root,int&ans){if(root==nullptr)return0;constintl=dfs(root->left,ans);constintr=dfs(root->right,ans);ans+=abs(l)+abs(r);return(root->val-1)+l+r;}};
classSolution{publicintdistributeCoins(TreeNoderoot){dfs(root);returnans;}privateintans=0;// Returns how many coins I can give (positive) / take (negative)privateintdfs(TreeNoderoot){if(root==null)return0;finalintl=dfs(root.left);finalintr=dfs(root.right);ans+=Math.abs(l)+Math.abs(r);return(root.val-1)+l+r;}}