方法1: DFS
divide-and-conquer: by dfs, all nodes of a subtree have val of 1, except that the root node of the subtree may have different values. The dfs process will deal with root node in left subtree and root node in right subtree, to make the substree root node have val of 1.
class Solution:
def distributeCoins(self, root: TreeNode) -> int:
return self.dfs(root)
def dfs(self, root):
if root is None:
return 0
left = self.dfs(root.left)
right = self.dfs(root.right)
res = (left + right)
if root.left:
tmp = root.left.val
root.left.val = 1
root.val += (tmp - 1)
res += abs(tmp - 1)
if root.right:
tmp = root.right.val
root.right.val = 1
root.val += (tmp - 1)
res += abs(tmp - 1)
return res
** Also tried iterative method that using parent node and the path for each node is to the root or to parent with value > 0, but it’s wrong in some cases, for example:
Input:
[0,0,null,0,0,4,null,null,0,3]
Output:
17
Expected:
15
In this case, the additional value doesn’t go to root, but to the forking node and then re-distribute.