leetcode 979. 在二叉树中分配硬币

手写思路

在这里插入图片描述

代码

/**
 * 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;
    }

};

猜你喜欢

转载自blog.csdn.net/skywuuu/article/details/115366863