LEETCODE ALGORITHM:979. Distribute Coins in Binary Tree
题目
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:
1 | Input: [3,0,0] |
Example 2:
1 | Input: [0,3,0] |
Example 3:
1 | Input: [1,0,2] |
Example 4:
1 | Input: [1,0,0,null,3] |
Note:
1<= N <= 100
0 <= node.val <= N
题解
1 | /** |
算法很巧妙,采用后序遍历从叶子节点开始,因为叶子只能从父节点拿硬币或向父节点送硬币,计算需要拿或送多少硬币,左右节点的需要拿或送硬币的和即为父节点需要硬币的进出状态,而所有拿或送硬币的数量即为答案,因为用正负来区分是取还是送,所以计算传递次数时要加绝对值。