Saturday, November 2, 2019

Leetcode 979: Distribute Coins in Binary Tree

https://leetcode.com/problems/distribute-coins-in-binary-tree/description/


Notes:

This question can be solved by recursion, which is usually employed for tree questions.

One way to think is using post-order recursion.

First of all, we need to figure out what should be returned. It should be the coins number from the left  + right + root->val - 1. Minus 1 because we need to keep one at root.

Then next, we should to ask: what is the moves required? If there are more coins than needed in a subtree, we need to move; but if there are less than needed, we also need to move!

Thus, we need to calculate the absolute values for the number of moves.

See the code below:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */

class Solution {
public:
    int distributeCoins(TreeNode* root) {
        res = 0;
        helper(root);
        return res;
    }

private:
    int res;
    int helper(TreeNode* root) {
        if(!root) return 0;
        int l = helper(root->left), r = helper(root->right);
        res += abs(l) + abs(r);
     //   cout<<res<<endl;
        return l + r + root->val - 1;
    }
};

No comments:

Post a Comment