979.在二叉树中分配硬币

979.在二叉树中分配硬币
给定一个有 N 个结点的二叉树的根结点 root,树中的每个结点上都对应有 node.val 枚硬币,并且总共有 N 枚硬币。

在一次移动中,我们可以选择两个相邻的结点,然后将一枚硬币从其中一个结点移动到另一个结点。(移动可以是从父结点到子结点,或者从子结点移动到父结点。)。

返回使每个结点上只有一枚硬币所需的移动次数。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/distribute-coins-in-binary-tree

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    int ans=0;
    public int distributeCoins(TreeNode root) {
        tvs(root,root);
        return ans;
    }
    public void tvs(TreeNode node,TreeNode root){
        if(node==null) return;
        tvs(node.left,node);
        tvs(node.right,node);
        if(node.val==0){
            ans+=1;
            node.val=1;
            root.val-=1;
        }
        else{
            root.val+=node.val-1;
            ans+= node.val>0 ? node.val-1 : 1-node.val;
        }
    }
}
发布了27 篇原创文章 · 获赞 2 · 访问量 759

猜你喜欢

转载自blog.csdn.net/qq_44028171/article/details/98754979