979. 在二叉树中分配硬币
题目描述
代码实现
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def distributeCoins(self, root: TreeNode) -> int:
# 定义post_order(root)为需要移动到它中或需要从它移动到它的父亲中的金币数量为 过载量
self.ans = 0
def post_order(root):
if not root:
return 0
L, R = post_order(root.left), post_order(root.right)
self.ans += abs(L) + abs(R)
return root.val + L + R - 1
post_order(root)
return self.ans