#979

Distribute Coins in Binary Tree

Medium
TreeDepth-First SearchBinary TreeDepth-First SearchTree Traversal
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal approach uses Depth-First Search (DFS) to calculate the number of coins that need to be moved up or down the tree, minimizing the total moves required.

⚙️

Algorithm

3 steps
  1. 1Step 1: Perform a DFS traversal of the tree.
  2. 2Step 2: For each node, calculate the excess or deficit of coins compared to 1 coin per node.
  3. 3Step 3: Accumulate the absolute values of excess/deficit to count the total moves.
solution.py19 lines
1# Full working Python code
2class TreeNode:
3    def __init__(self, val=0, left=None, right=None):
4        self.val = val
5        self.left = left
6        self.right = right
7
8class Solution:
9    def distributeCoins(self, root: TreeNode) -> int:
10        self.moves = 0
11        def dfs(node):
12            if not node:
13                return 0
14            left = dfs(node.left)
15            right = dfs(node.right)
16            self.moves += abs(left) + abs(right)
17            return node.val + left + right - 1
18        dfs(root)
19        return self.moves

Complexity note: The complexity is O(n) because we visit each node exactly once during the DFS traversal.

  • 1The total number of coins is equal to the number of nodes, ensuring that redistribution is always possible.
  • 2DFS is a powerful technique for tree problems, allowing us to efficiently traverse and calculate values.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.