LC 979. Distribute Coins in Binary Tree

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

In one move, we may choose two adjacent nodes and move one coin from one node to another.  (The move may be from parent to child, or from child to parent.)

Return the number of moves required to make every node have exactly one coin.

Runtime: 4 ms, faster than 100.00% of C++ online submissions for Distribute Coins in Binary Tree.

class Solution {
private:
  int ret;
public:
  int distributeCoins(TreeNode* root) {
    ret = 0;
    helper(root);
    return ret;
  }
  int helper(TreeNode* root) {
    if(!root) return 0;
    int left = helper(root->left), right = helper(root->right);
    ret += abs(left) + abs(right);
    return left + right + root->val - 1;
  }
};
原文地址:https://www.cnblogs.com/ethanhong/p/10300865.html