手写思路

代码
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int count = 0; // 记录次数
int distributeCoins(TreeNode* root) {
countCoins(root);
return count;
}
int countCoins(TreeNode* root){
if(root){
int left_coins = countCoins(root->left);
int right_coins = countCoins(root->right);
count += abs(left_coins) + abs(right_coins); // 移动次数
return left_coins + right_coins +root->val - 1; // 当前节点的金币数-1
}
return 0;
}
};

本文介绍了一种解决二叉树中金币分配问题的算法。通过递归计算每个节点的金币数并调整移动次数,最终得出使每个节点金币数为1所需的最小移动次数。
385

被折叠的 条评论
为什么被折叠?



