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
π 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 + rightBalanceThe
-1accounts for the one candy that should remain at the current node.leftBalanceandrightBalancerepresent 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++)
β‘ View Alternative Approaches with Code and Analysis
π 2οΈβ£ Post-Order Traversal with Balance Tracking
π‘ Algorithm Steps:
Process children nodes before parent using post-order traversal.
Calculate excess or deficit candies at each node.
Accumulate absolute values of imbalances as total moves.
Propagate net balance upward to parent nodes.
π Complexity Analysis:
Time: β±οΈ O(n) - Visit each node exactly once
Auxiliary Space: πΎ O(h) - Recursion stack depth equals tree height
β
Why This Approach?
Clear separation of balance calculation and move counting
Lambda recursion pattern for modern C++
Easy to trace flow of candy redistribution
π 3οΈβ£ Iterative Stack-Based Approach
π‘ Algorithm Steps:
Use explicit stack to simulate post-order traversal iteratively.
Track visited nodes to ensure children are processed first.
Calculate balance for each node after processing children.
Sum absolute balances to get total distribution moves.
π Complexity Analysis:
Time: β±οΈ O(n) - Each node pushed and popped once
Auxiliary Space: πΎ O(n) - Stack and hashmap storage
β
Why This Approach?
Avoids recursion for large trees
Explicit control over traversal order
Useful when recursion depth is a concern
π 4οΈβ£ Post-Order with HashMap Storage
π‘ Algorithm Steps:
Perform post-order traversal storing balance in hashmap.
Calculate balance for left and right children from hashmap.
Store current node's balance for parent lookup.
Accumulate moves based on absolute child balances.
π Complexity Analysis:
Time: β±οΈ O(n) - Single pass through all nodes
Auxiliary Space: πΎ O(n) - Hashmap for balance storage
β
Why This Approach?
Explicit post-order pattern demonstration
Balance storage for potential further operations
Clear separation of concerns in logic
π 5οΈβ£ Helper Function Approach
π‘ Algorithm Steps:
Create separate helper function to handle recursion.
Pass moves counter by reference to update across calls.
Calculate balance and update moves in helper function.
Return balance value for parent node calculation.
π Complexity Analysis:
Time: β±οΈ O(n) - Visit each node once
Auxiliary Space: πΎ O(h) - Recursion stack space
β
Why This Approach?
Traditional recursive pattern
Easy to understand for beginners
Clear separation between main and helper functions
π π Comparison of Approaches
π Approach
β±οΈ Time Complexity
πΎ Space Complexity
β Pros
β οΈ Cons
π― Lambda DFS
π’ O(n)
π’ O(h)
π Most concise & elegant
π§ Requires C++11 features
π Balance Tracking
π’ O(n)
π’ O(h)
π Clear logic flow
π Slightly verbose
π Iterative Stack
π’ O(n)
π‘ O(n)
π― No recursion limits
π More complex implementation
π§΅ Post-Order Map
π’ O(n)
π‘ O(n)
β Balance reusability
πΎ Extra space overhead
π§ Helper Function
π’ O(n)
π’ O(h)
π Traditional & clear
π More lines of code
π Best Choice Recommendation
π― Scenario
ποΈ Recommended Approach
π₯ Performance Rating
π Optimal code brevity
π₯ Lambda DFS
β β β β β
π Interview explanation
π₯ Balance Tracking
β β β β β
π§ Deep recursion concern
π₯ Iterative Stack
β β β ββ
π― Competitive programming
π Lambda DFS
β β β β β
π Learning/Educational
ποΈ Helper Function
β β β β β
β Code (Java)
π Code (Python)
π§ 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