Leetcode 979: Distribute Coins in Binary Tree

grid47
grid47
Exploring patterns and algorithms
Aug 1, 2024 6 min read

You are given a binary tree with n nodes, where each node contains node.val coins. There are exactly n coins in total across the tree. In one move, you can transfer a coin between two adjacent nodes (parent to child or child to parent). Return the minimum number of moves required to ensure that every node has exactly one coin.
Problem
Approach
Steps
Complexity
Input: A binary tree represented by an array of integers, where each integer corresponds to the number of coins at that node.
Example: root = [1, 0, 0]
Constraints:
• 1 <= n <= 100
• 0 <= Node.val <= n
• The sum of all Node.val is n.
Output: Return the minimum number of moves required to make every node have exactly one coin.
Example: 2
Constraints:
• The output must be an integer representing the minimum number of moves.
Goal: We need to calculate the minimum moves by redistributing coins across the binary tree.
Steps:
• Traverse the tree recursively.
• For each node, calculate the difference between the node's coin count and the desired coin count (which is 1).
• Accumulate the total moves by summing the absolute differences in coin count for each subtree.
• Return the total number of moves.
Goal: The input binary tree must satisfy the given constraints.
Steps:
• 1 <= n <= 100
• 0 <= Node.val <= n
• The sum of all Node.val is n.
Assumptions:
• The tree is well-formed, and all nodes are valid.
Input: root = [1, 0, 0]
Explanation: The root node has one coin, and both children have none. The solution involves moving coins from the root to its children to balance the tree.

Input: root = [0, 2, 0]
Explanation: In this case, two coins are initially at the left child. We move coins to the root and then move one coin to the right child.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus