LeetCode 979. Distribute Coins in Binary Tree python解题报告

979. Distribute Coins in Binary Tree

  1. Distribute Coins in Binary Treepython solution

题目描述

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.
在这里插入图片描述在这里插入图片描述

解析

最后的平衡状态是每个节点都有一个硬币,这里仍然要采用递归的方法求得左右子树的不平衡个数。最终硬币需要移动的步数之和,就是左子树的不平和加上右子树的不平衡之和。以example2 为例,左子树的不平衡状态为2,就相当于将两个多余的硬币移动到了root节点。右子树的不平衡状态为1,相当于从上次已经移动到root节点的2个硬币中取出一个,移动到右子树。所以,整体需要移动步数是左子树不平衡个数的绝对值加上右子树不平衡个数的绝对值。
解释下为何
return node.val+leftcount+rightcount-1而不是
return node.val+abs(leftcount)+abs(rightcount)-1
因为存在计数作用的count,coun是计算左右子树不平衡绝对值之和。在每次dfs结束后,向上一级返回该节点以下的整体情况,若其本身已经达到平衡状态0,则不需要从其他节点调硬币过来,这种行为就会产生冗余步骤。

// An highlighted block
class Solution:
    def distributeCoins(self, root: TreeNode) -> int:
        self.count=0
        def dfs(node):
            if not node: 
                return 0
            leftcount=dfs(node.left)
            rightcount=dfs(node.right)
            self.count+=abs(leftcount)+abs(rightcount)
            return node.val+leftcount+rightcount-1
        dfs(root)
        return self.count

Reference

https://leetcode.com/problems/distribute-coins-in-binary-tree/discuss/407577/Python-DFS

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值