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, we can select 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. Find the minimum number of moves required to ensure that every node in the tree has exactly one candy.
Output: 6 Explanation: Move 1 candy from root to root->left node Move 1 candy from root to root->right node Move 1 candy from root->right node to root->right->left node Move 1 candy from root to root->right child Move 1 candy from root->right node to root->right->right node Move 1 candy from root to root->right node So, total 6 moves required.
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.
[Expected Approach - 1] Using Recursion - O(n) Time and O(h) Space
The idea is to use recursion to traverse the tree from leaf to root and consecutively balance all of the nodes. To balance a node, the number of candy at that node must be 1.
There can be two cases:
If a node needs candies, if the node of the tree has 0 candies then we should push a candy from its parent onto the node.
If the node has more than 1 candy. ex. 4 candies (an excess of 3), then we should push 3 candies off the node to its parent.
So, the total number of moves from that leaf to or from its parent is excess = abs(numCandies - 1). Once a node is balanced, we never have to consider this node again in the rest of our calculation.
Output
6
[Expected Approach - 2] Using Iteration - O(n) Time and O(n) Space
At each node, some candies will come from the left and goes to the right or vice versa. At each case, moves will increase. So, for each node we will count number of required candies in the right child and in left child i.e (total number of node - total candies) for each child. It is possible that it might be less than 0 but in that case too it will counted as move because extra candies also has to travel through the root node.
Steps:
We use a stack to traverse the tree in post-order without recursion.
Track each node’s state to ensure children are processed before the parent.
We use a map to store excess candies at each node: excess = nodeCandies + leftExcess + rightExcess - 1.
Count moves as abs(leftExcess) + abs(rightExcess).
Pass the node’s excess to its parent.
Repeat until the root is processed; total moves give the minimum required.