2023-07-14 LeetCode Daily Question (Distribute Coins in Binary Tree)

2023-07-14 One question per day

1. Topic number

979. 在二叉树中分配硬币

2. Topic link

Click to jump to the topic location

3. Topic description

Given the root node root of a binary tree with N nodes, each node in the tree corresponds to node.val coins, and there are N coins in total.

In one move, we can select two adjacent nodes and move a coin from one of them to the other. (Movement can be from parent node to child node, or from child node to parent node.).

Returns the number of moves required to get only one coin on each node.

hint:

  1. 1<= N <= 100
  2. 0 <= node.val <= N

4. Problem solving code

/**
 * 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 res = 0;
    int dfs(TreeNode* root){
    
    
        if(root == nullptr){
    
    
            return 0;
        }
        int move_left = 0; // 硬币在左子树所需要移动的个数
        int move_right = 0; // 硬币在右子树所需要移动的个数
        if(root->left){
    
    
            move_left = dfs(root->left);
        }
        if(root->right){
    
    
            move_right = dfs(root->right);
        }
        res += abs(move_left) + abs(move_right);
    return move_left + move_right + root->val - 1;
    }
    int distributeCoins(TreeNode* root) {
    
    
        dfs(root);
    return res;
    }
};

Five, problem-solving ideas

(1) First we think about a problem, how to move coins in a tree.

(2) The simplest way of thinking is a tree, with coins moving on the left and coins moving on the right, then the number of moves that needs to be made is the number of coin moves on the left + the number of coin moves on the right.

(3) But there is the problem. For example, now there is a subtree with three nodes (two nodes on the left and right), the left subtree has 3 coins, the right subtree has no coins, and the root has no. Then the number of coins that need to be moved in the left subtree is 3 - 1. The number of moves of the right subtree is set to 0-1 and the absolute value is equal to 1. And because the two left and right node subtrees do not need coins, so when recursing, the number of left and right moves is 0. It needs to be added when actually recursive.

(4) Return the result at last.

Guess you like

Origin blog.csdn.net/qq_56086076/article/details/131715654