[LeetCode] 979. Distribute Coins in Binary Tree
You are given the root of a binary tree with n nodes where each node in the tree has node.val coins. There are n coins in total throughout the whole tree.
In one move, we may choose two adjacent nodes and move one coin from one node to another. A move may be from parent to child, or from child to parent.
Return the minimum number of moves required to make every node have exactly one coin.
Example 1:
Input: root = [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: root = [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.
Constraints:
The number of nodes in the tree is n.
1 <= n <= 100
0 <= Node.val <= n
The sum of all Node.val is n.
在二叉树中分配硬币。
给定一个有 N 个结点的二叉树的根结点 root,树中的每个结点上都对应有 node.val 枚硬币,并且总共有 N 枚硬币。在一次移动中,我们可以选择两个相邻的结点,然后将一枚硬币从其中一个结点移动到另一个结点。(移动可以是从父结点到子结点,或者从子结点移动到父结点。)。
返回使每个结点上只有一枚硬币所需的移动次数。
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/distribute-coins-in-binary-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路
思路是后序遍历。这道题的后续遍历不太容易想到,因为最后要求的东西跟你在后序遍历里往父节点送的信息是不一样的。
这里有几个细节需要想明白,
因为我们最后要求的是硬币的移动次数,所以我们不需要把树变成图,对于没有硬币的节点,我们只需要让他往自己的父节点送出“我和我的左右子树一共需要X个硬币”这个信息即可。
对于硬币不足的节点,他往父节点送的那个值是负的;但是对于硬币很多的节点,他往父节点送的那个值是正的。
res 统计的是硬币移动的步数,跟某个节点需要多少个硬币无关,所以在累加的时候要取绝对值。
复杂度
时间O(n)
空间O(n)
代码
Java实现
1 |
|