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:

  1. /**
  2.  * Definition for a binary tree node.
  3.  * struct TreeNode {
  4.  *     int val;
  5.  *     TreeNode *left;
  6.  *     TreeNode *right;
  7.  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
  8.  * };
  9.  */
  10. class Solution {
  11. public:
  12.     int distributeCoins(TreeNode* root) {
  13.         res = 0;
  14.         helper(root);
  15.         return res;
  16.     }
  17. private:
  18.     int res;
  19.     int helper(TreeNode* root) {
  20.         if(!root) return 0;
  21.         int l = helper(root->left), r = helper(root->right);
  22.         res += abs(l) + abs(r);
  23.      //   cout<<res<<endl;
  24.         return l + r + root->val - 1;
  25.     }
  26. };

No comments:

Post a Comment