12. Distribute Candies
β GFG solution to the Distribute Candies in Binary Tree problem: find minimum moves to distribute candies such that each node has exactly one candy using post-order DFS traversal. π
The problem can be found at the following link: π Question Link
π§© Problem Description
You are given the root of a binary tree with n
nodes, where each node contains a certain number of candies, and the total number of candies across all nodes is n
. In one move, you can select any two adjacent nodes and transfer one candy from one node to the other. The transfer can occur between a parent and child in either direction.
The task is to determine the minimum number of moves required to ensure that every node in the tree has exactly one candy.
Note: The testcases are framed such that it is always possible to achieve a configuration in which every node has exactly one candy, after some moves.
π Examples
Example 1
Input: root = [5, 0, 0, N, N, 0, 0]
Output: 6
Explanation:
Move 1 candy from root to left child
Move 1 candy from root to right child
Move 1 candy from right child to root->right->left node
Move 1 candy from root to right child
Move 1 candy from right child to root->right->right node
Move 1 candy from root to right child
So, total 6 moves required.
Example 2
Input: root = [2, 0, 0, N, N, 3, 0]
Output: 4
Explanation:
Move 1 candy from root to left child
Move 1 candy from root->right->left node to root->right node
Move 1 candy from root->right node to root->right->right node
Move 1 candy from root->right->left node to root->right node
So, total 4 moves required.
π Constraints
$1 \le n \le 3 \times 10^3$
$0 \le \text{Node->data} \le n$
The sum of all Node->data = n
β
My Approach
The optimal approach uses Post-Order DFS Traversal with Balance Calculation to efficiently compute the minimum number of candy distribution moves:
Post-Order DFS with Balance Tracking
Base Case:
If the current node is null, return 0 (no candies to balance).
Recursive Traversal:
Recursively compute the balance for the left subtree.
Recursively compute the balance for the right subtree.
Balance represents excess (positive) or deficit (negative) candies.
Calculate Node Balance:
For each node, calculate:
balance = node->data - 1 + leftBalance + rightBalance
The
-1
accounts for the one candy that should remain at the current node.leftBalance
andrightBalance
represent candies flowing from children.
Count Moves:
Add
abs(balance)
to the total moves counter.The absolute value represents candies that must pass through this node's edge with its parent.
Return Balance:
Return the computed balance to the parent node for further calculation.
Key Insight:
Each edge between parent and child will transfer exactly
|balance|
candies.The direction (up or down) doesn't matter; we only count the number of transfers.
Post-order traversal ensures children are processed before parents.
π Time and Auxiliary Space Complexity
Expected Time Complexity: O(n), where n is the number of nodes in the binary tree. We visit each node exactly once during the DFS traversal to calculate balance and accumulate moves.
Expected Auxiliary Space Complexity: O(h), where h is the height of the binary tree. This space is used by the recursion call stack during DFS traversal. In the worst case of a skewed tree, h = n, making it O(n). For a balanced tree, h = log(n), making it O(log n).
π§βπ» Code (C++)
class Solution {
public:
int distCandy(Node* root) {
int moves = 0;
function<int(Node*)> dfs = [&](Node* n) {
if (!n) return 0;
int bal = n->data - 1 + dfs(n->left) + dfs(n->right);
moves += abs(bal);
return bal;
};
dfs(root);
return moves;
}
};
β Code (Java)
class Solution {
int moves = 0;
public int distCandy(Node root) {
dfs(root);
return moves;
}
int dfs(Node n) {
if (n == null) return 0;
int bal = n.data - 1 + dfs(n.left) + dfs(n.right);
moves += Math.abs(bal);
return bal;
}
}
π Code (Python)
class Solution:
def distCandy(self, root):
self.moves = 0
def dfs(n):
if not n: return 0
bal = n.data - 1 + dfs(n.left) + dfs(n.right)
self.moves += abs(bal)
return bal
dfs(root)
return self.moves
π§ Contribution and Support
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: π¬ Any Questions?. Let's make this learning journey more collaborative!
β If you find this helpful, please give this repository a star! β
πVisitor Count
Last updated