979. Distribute Coins in Binary Tree

Photo by Traxer on Unsplash

979. Distribute Coins in Binary Tree

# 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: Optional[TreeNode]) -> int:
        moves = 0
        def dfs(node, excess): 
            nonlocal moves

            if not node:
                return 0

            excessLeft = dfs(node.left, excess)
            excessRight = dfs(node.right, excess)

            # excess coins at a level (self + left + right)
            excess = node.val - 1 + excessLeft + excessRight

            moves += abs(excessLeft) + abs(excessRight)

            return excess 


        dfs(root, 0)

        return moves