LeetCode solutions

1021. Distribute Coins in Binary Tree

My accepted Python solution to LeetCode problem 1021, Distribute Coins in Binary Tree, running in 3ms.

  • Difficulty: Medium
  • Python
  • Runtime 3ms
  • Memory 17.4MB

Read the problem on LeetCode View on GitHub

Python

Accepted on LeetCode — runtime 3ms, memory 17.4MB, accepted 2025-12-30.

python
# 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:
        self.moves = 0
        
        def dfs(node):
            if not node:
                return 0
            
            left_excess = dfs(node.left)
            right_excess = dfs(node.right)
            
            # Number of moves is the absolute flow through each edge
            self.moves += abs(left_excess) + abs(right_excess)
            
            # Return excess coins from this subtree (coins - 1 for each node)
            return node.val - 1 + left_excess + right_excess
        
        dfs(root)
        return self.moves

Source