leetcode979 - Distribute Coins in Binary Tree - medium

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.

 

Example 1:

Input: [3,0,0]
Output: 2
Explanation: From the root of the tree, we move one coin to its left child, and one coin to its right child.

Example 2:

Input: [0,3,0]
Output: 3
Explanation: From the left child of the root, we move two coins to the root [taking two moves].  Then, we move one coin from the root of the tree to the right child.

Example 3:

Input: [1,0,2]
Output: 2

Example 4:

Input: [1,0,0,null,3]
Output: 4

 

Note:

  1. 1<= N <= 100
  2. 0 <= node.val <= N
 
对于一组(node和它的俩子node), move的次数,就是在这(至多)两条path上,来也好去也好,钱流动过几次。每个node最后都该是1,那钱要流动,就看看当前它的net balance是多少。还是先focus在一组nodes里,我们希望parent node能先帮子node满足条件,作为一个子node我就算多了50,少了80,我还是先和我的的parent分,再由parent去找他的parent分,tree是connected,总归能分好。所以,recursion里做两件事,1.算清我自己现在的net balance,也就是我本身val-1再加我的子node的balance;2. 把我和我子node相互交流了多少加到最后的结果里,用绝对值,加加减减都要算的。
 
实现:Time O(n), Space O(n)
class Solution {
public:
    int netVal(TreeNode* node, int& res){
        if (!node)
            return 0;
        int flowL = netVal(node->left, res);
        int flowR = netVal(node->right, res);
        res += abs(flowL)+abs(flowR);
        return node->val-1+flowL+flowR;
    }
        
    int distributeCoins(TreeNode* root) {
        int res = 0;
        netVal(root, res);
        return res;
    }
};

 

posted @ 2020-10-29 14:56  little_veggie  阅读(61)  评论(0)    收藏  举报