搞不定这种递归计算,可能我的头脑是“线性”的,这种一层一层的,想起来太费劲了,想的头发都没了。以后希望能有AI来写这种程序吧,AI不怕掉头发!
class Solution(object):
def __init__(self):
self.res = 0 def dfs(self,root):
if not root:
return 0
left = self.dfs(root.left)
right = self.dfs(root.right)
self.res += abs(left) + abs(right)
return root.val + left + right - 1 def distributeCoins(self, root: TreeNode) -> int:
self.dfs(root)
return self.res