979. Distribute Coins in Binary Tree
- 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