Open In App

Distribute candies in a Binary Tree

Last Updated : 11 Jul, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

You are given 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.
The task is to determine the minimum number of moves required to ensure that every node in the tree has exactly one candy.

Examples: 

Input:

distribute-candies-in-a-binary-tree-1

Output: 2
Explanation: From the root of the tree, we move one candy to its left child, and one candy to its right child.

Input:

distribute-candies-in-a-binary-tree-2

Output: 3
Explanation: From the left child of the root, we move two candies to the root [taking two moves]. Then, we move one candy from the root of the tree to the right child.

[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:  

  1. If a node needs candies, if the node of the tree has 0 candies (an excess of -1 from what it needs), then we should push a candy from its parent onto the node.
  2. If the node has more than 1 candy. If it has say, 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(num_candies - 1). Once a node is balanced, we never have to consider this node again in the rest of our calculation.

Below is the implementation of the above approach: 

C++
// C ++ Recursive Implementation to find
// the minimum number of moves required such 
// that every node has exactly one candy.
#include <bits/stdc++.h>
using namespace std;

class Node {
public:
    int data;
    Node* left;
    Node* right;

    Node(int x) {
        data = x;
        left = right = nullptr;
    }
};

// Utility function to find the number of
// moves to distribute all of the candies
int distributeCandyUtil(Node* root, int& ans) {
  
    // Base Case
    if (root == nullptr)
        return 0;

    // Traverse left subtree
    int l = distributeCandyUtil(root->left, ans);

    // Traverse right subtree
    int r = distributeCandyUtil(root->right, ans);

    // Update number of moves
    ans += abs(l) + abs(r);

    // Return number of moves to balance
    // current node
    return root->data + l + r - 1;
}

// Function to find the number of moves to
// distribute all of the candies
int distributeCandy(Node* root) {
    int ans = 0;

    distributeCandyUtil(root, ans);

    return ans;
}

int main() {
    
    // Representation of given Binary Tree
    //    3
    //   / \
    //  0   0
    Node* root = new Node(3);
    root->left = new Node(0);
    root->right = new Node(0);

    cout << distributeCandy(root);

    return 0;
}
Java
// Java Recursive Implementation to find
// the minimum number of moves required such 
// that every node has exactly one candy.
class Node {
    public int data;
    public Node left, right;

    public Node(int x) {
        data = x;
        left = right = null;
    }
}

class GfG {
  
    // Utility function to find the number of
    // moves to distribute all of the candies
    static int distributeCandyUtil(Node root, int[] ans) {

        // Base Case
        if (root == null)
            return 0;

        // Traverse left subtree
        int l = distributeCandyUtil(root.left, ans);

        // Traverse right subtree
        int r = distributeCandyUtil(root.right, ans);

        // Update number of moves
        ans[0] += Math.abs(l) + Math.abs(r);

        // Return number of moves to balance
        // current node
        return root.data + l + r - 1;
    }

    // Function to find the number of moves to
    // distribute all of the candies
    static int distributeCandy(Node root) {
        int[] ans = new int[1];

        distributeCandyUtil(root, ans);

        return ans[0];
    }

    public static void main(String[] args) {
        
        // Representation of given Binary Tree
        //    3
        //   / \
        //  0   0
        Node root = new Node(3);
        root.left = new Node(0);
        root.right = new Node(0);

        System.out.println(distributeCandy(root));
    }
}
Python
# Python Recursive Implementation to find
# the minimum number of moves required such 
# that every node has exactly one candy.
class Node:
    def __init__(self, x):
        self.data = x
        self.left = None
        self.right = None

# Utility function to find the number of
# moves to distribute all of the candies
def distribute_candy_util(root, ans):
    
    # Base Case
    if root is None:
        return 0

    # Traverse left subtree
    l = distribute_candy_util(root.left, ans)

    # Traverse right subtree
    r = distribute_candy_util(root.right, ans)

    # Update number of moves
    ans[0] += abs(l) + abs(r)

    # Return number of moves to balance
    # current node
    return root.data + l + r - 1

# Function to find the number of moves to
# distribute all of the candies
def distribute_candy(root):
    ans = [0]
    
    distribute_candy_util(root, ans)
    
    return ans[0]

if __name__ == "__main__":
    
    # Representation of given Binary Tree
    #    3
    #   / \
    #  0   0
    root = Node(3)
    root.left = Node(0)
    root.right = Node(0)

    print(distribute_candy(root))
C#
// C# Recursive Implementation to find
// the minimum number of moves required such 
// that every node has exactly one candy.
using System;

class Node {
    public int data;
    public Node left, right;

    public Node(int x) {
        data = x;
        left = right = null;
    }
}

// Utility function to find the number of
// moves to distribute all of the candies
class GfG {
    static int distributeCandyUtil(Node root, ref int ans) {

        // Base Case
        if (root == null)
            return 0;

        // Traverse left subtree
        int l = distributeCandyUtil(root.left, ref ans);

        // Traverse right subtree
        int r = distributeCandyUtil(root.right, ref ans);

        // Update number of moves
        ans += Math.Abs(l) + Math.Abs(r);

        // Return number of moves to balance
        // current node
        return root.data + l + r - 1;
    }

    // Function to find the number of moves to
    // distribute all of the candies
    static int distributeCandy(Node root) {
        int ans = 0;
        distributeCandyUtil(root, ref ans);
        return ans;
    }
  
    static void Main(string[] args) {
        
        // Representation of given Binary Tree
        //    3
        //   / \
        //  0   0
        Node root = new Node(3);
        root.left = new Node(0);
        root.right = new Node(0);
      
        Console.WriteLine(distributeCandy(root));
    }
}
JavaScript
// JavaScript Recursive Implementation to find
// the minimum number of moves required such 
// that every node has exactly one candy.
class Node {
    constructor(x) {
        this.data = x;
        this.left = null;
        this.right = null;
    }
}

// Utility function to find the number of
// moves to distribute all of the candies
function distributeCandyUtil(root, ans) {

    // Base Case
    if (root === null)
        return 0;

    // Traverse left subtree
    let l = distributeCandyUtil(root.left, ans);

    // Traverse right subtree
    let r = distributeCandyUtil(root.right, ans);

    // Update number of moves
    ans.moves += Math.abs(l) + Math.abs(r);

    // Return number of moves to balance
    // current node
    return root.data + l + r - 1;
}

// Function to find the number of moves to
// distribute all of the candies
function distributeCandy(root) {
    let ans = { moves: 0 };
    
    distributeCandyUtil(root, ans);
    
    return ans.moves;
}

// Representation of given Binary Tree
//    3
//   / \
//  0   0
let root = new Node(3);
root.left = new Node(0);
root.right = new Node(0);

console.log(distributeCandy(root));

Output
2

[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 comes from the right and goes to left. 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.

Below is the implementation of the above approach:

C++
// C++ Iterative Implementation to find
// the minimum number of moves required such 
// that every node has exactly one candy.
#include <bits/stdc++.h>
using namespace std;

class Node {
public:

    int data;
    Node* left;
    Node* right;
  
    Node(int x) {
        data = x;
        left = right = nullptr;
    }
};

// Function to find the number of moves to
// distribute all of the candies using 
// an iterative approach
int distributeCandy(Node* root) {

    if (root == nullptr) return 0;
    int ans = 0;

    stack<pair<Node*, int>> stk;

    // Map to store balance of candies at each node
    unordered_map<Node*, int> balance;

    // Push root node into the stack 
    // with state 0 (not processed)
    stk.push({root, 0});

    while (!stk.empty()) {

        // Get the top node and its state 
        // from the stack
        auto curr = stk.top();
        auto node = curr.first;
        auto state = curr.second;
        stk.pop();

        if (node == nullptr) continue;

        // If state is 0, push node back with 
        // state 1 (post-processing)
        if (state == 0) {

            // Push current node back with 
            // state 1 for post-order processing
            stk.push({node, 1});

            stk.push({node->left, 0});

            stk.push({node->right, 0});

        } 
        else {

            // Get balance of left child
            int leftBalance = balance[node->left];

            // Get balance of right child
            int rightBalance = balance[node->right];

            // Add moves required for left and right subtrees
            ans += abs(leftBalance) + abs(rightBalance);

            // Calculate current node's balance: (candies - 1)
            balance[node] 
              = node->data + leftBalance + rightBalance - 1;
        }
    }
  
    return ans;
}

int main() {
    
    // Representation of given Binary Tree
    //    3
    //   / \
    //  0   0
    Node* root = new Node(3);
    root->left = new Node(0);
    root->right = new Node(0);

    cout << distributeCandy(root);

    return 0;
}
Java
// Java Iterative Implementation to find
// the minimum number of moves required such 
// that every node has exactly one candy.
import java.util.Stack;
import java.util.HashMap;

class Node {

    int data;
    Node left;
    Node right;
  
    Node(int x) {
        data = x;
        left = right = null;
    }
}

class Pair<K, V> {

    private K key;
    private V value;
  
    public Pair(K key, V value) {
        this.key = key;
        this.value = value;
    }

    // Method to get the key
    public K getKey() {
        return key;
    }

    // Method to get the value
    public V getValue() {
        return value;
    }

    // Method to set the key
    public void setKey(K key) {
        this.key = key;
    }

    // Method to set the value
    public void setValue(V value) {
        this.value = value;
    }
}

// Function to find the number of moves to
// distribute all of the candies using 
// an iterative approach
class GfG {

    static int distributeCandy(Node root) {

        if (root == null) return 0;
        int ans = 0;

        Stack<Pair<Node, Integer>> stk = new Stack<>();

        // Map to store balance of candies at each node
        HashMap<Node, Integer> balance = new HashMap<>();

        // Push root node into the stack 
        // with state 0 (not processed)
        stk.push(new Pair<>(root, 0));

        while (!stk.isEmpty()) {

            // Get the top node and its state 
            // from the stack
            Pair<Node, Integer> curr = stk.pop();
            Node node = curr.getKey();
            int state = curr.getValue();

            if (node == null) continue;

            // If state is 0, push node back with 
            // state 1 (post-processing)
            if (state == 0) {

                // Push current node back with 
                // state 1 for post-order processing
                stk.push(new Pair<>(node, 1));

                stk.push(new Pair<>(node.left, 0));

                stk.push(new Pair<>(node.right, 0));

            } 
            else {

                // Get balance of left child
                int leftBalance 
                         = balance.getOrDefault(node.left, 0);

                // Get balance of right child
                int rightBalance 
                         = balance.getOrDefault(node.right, 0);

                // Add moves required for left and right subtrees
                ans += Math.abs(leftBalance) 
                            + Math.abs(rightBalance);

                // Calculate current node's balance: (candies - 1)
                balance.put(node, node.data 
                            + leftBalance + rightBalance - 1);
            }
        }

        // Return the total number of moves
        return ans;
    }

    public static void main(String[] args) {
        
        // Representation of given Binary Tree
        //    3
        //   / \
        //  0   0
        Node root = new Node(3);
        root.left = new Node(0);
        root.right = new Node(0);

        System.out.println(distributeCandy(root));
    }
}
Python
# Python Iterative Implementation to find
# the minimum number of moves required such 
# that every node has exactly one candy.

class Node:
    def __init__(self, x):
        self.data = x
        self.left = None
        self.right = None

# Function to find the number of moves to
# distribute all of the candies using 
# an iterative approach
def distributeCandy(root):
    
    if root is None:
        return 0

    ans = 0

    stk = []

    # Dictionary to store balance of
    # candies at each node
    balance = {}

    # Push root node into the stack 
    # with state 0 (not processed)
    stk.append((root, 0))

    while stk:

        # Get the top node and its state 
        # from the stack
        curr = stk.pop()
        node = curr[0]
        state = curr[1]

        if node is None:
            continue

        # If state is 0, push node back with 
        # state 1 (post-processing)
        if state == 0:

            # Push current node back with 
            # state 1 for post-order processing
            stk.append((node, 1))

            stk.append((node.left, 0))

            stk.append((node.right, 0))

        else:

            # Get balance of left child
            left_balance = balance.get(node.left, 0)

            # Get balance of right child
            right_balance = balance.get(node.right, 0)

            # Add moves required for left and right subtrees
            ans += abs(left_balance) + abs(right_balance)

            # Calculate current node's balance: (candies - 1)
            balance[node] = node.data + left_balance + right_balance - 1

    return ans

if __name__ == "__main__":
    
    # Representation of given Binary Tree
    #    3
    #   / \
    #  0   0
    root = Node(3)
    root.left = Node(0)
    root.right = Node(0)

    print(distributeCandy(root))
C#
// C# Iterative Implementation to find
// the minimum number of moves required such 
// that every node has exactly one candy.
using System;
using System.Collections.Generic;

class Node {
    public int data;
    public Node left;
    public Node right;

    public Node(int x) {
        data = x;
        left = null;
        right = null;
    }
}

class GfG {
  
    // Function to find the number of moves to
    // distribute all of the candies using 
    // an iterative approach
    static int distributeCandy(Node root) {

        if (root == null) return 0;

        int ans = 0;

        Stack<(Node, int)> stk
                   = new Stack<(Node, int)>();

        // Dictionary to store balance of 
      	// candies at each node
        Dictionary<Node, int> balance
                   = new Dictionary<Node, int>();

        // Push root node into the stack 
        // with state 0 (not processed)
        stk.Push((root, 0));

        while (stk.Count > 0) {

            // Get the top node and its state 
            // from the stack
            var curr = stk.Pop();
            var node = curr.Item1;
            var state = curr.Item2;

            if (node == null) continue;

            // If state is 0, push node back with 
            // state 1 (post-processing)
            if (state == 0) {

                // Push current node back with 
                // state 1 for post-order processing
                stk.Push((node, 1));

                stk.Push((node.left, 0));

                stk.Push((node.right, 0));

            } 
            else {

                
                // Get balance of left child, handle nulls
                int left_balance = (node.left != null 
                            && balance.ContainsKey(node.left)) 
                            ? balance[node.left] : 0;

                // Get balance of right child, handle nulls
                int right_balance = (node.right != null
                            && balance.ContainsKey(node.right)) 
                             ? balance[node.right] : 0;

                // Add moves required for left and right subtrees
                ans += Math.Abs(left_balance)
                              + Math.Abs(right_balance);

                // Calculate current node's balance: (candies - 1)
                balance[node] 
                  = node.data + left_balance + right_balance - 1;
            }
        }
      
        return ans;
    }

    static void Main() {

        // Representation of given Binary Tree
        //    3
        //   / \
        //  0   0
        Node root = new Node(3);
        root.left = new Node(0);
        root.right = new Node(0);

        Console.WriteLine(distributeCandy(root));
    }
}
JavaScript
// JavaScript Iterative Implementation to find
// the minimum number of moves required such 
// that every node has exactly one candy.

class Node {
    constructor(x) {
        this.data = x;
        this.left = null;
        this.right = null;
    }
}

// Function to find the number of moves to
// distribute all of the candies using 
// an iterative approach
function distributeCandy(root) {

    if (root === null) return 0;

    let ans = 0;

    const stk = [];

    // Map to store balance of candies
    // at each node
    const balance = new Map();

    // Push root node into the stack 
    // with state 0 (not processed)
    stk.push([root, 0]);

    while (stk.length > 0) {

        // Get the top node and its state 
        // from the stack
        const [node, state] = stk.pop();

        if (node === null) continue;

        // If state is 0, push node back with 
        // state 1 (post-processing)
        if (state === 0) {

            // Push current node back with 
            // state 1 for post-order processing
            stk.push([node, 1]);

            stk.push([node.left, 0]);
            stk.push([node.right, 0]);

        } 
        else {

            // Get balance of left child, 
            // handle nulls
            const left_balance = node.left && balance.has(node.left) 
                ? balance.get(node.left) 
                : 0;

            // Get balance of right child, handle nulls
            const right_balance = node.right && balance.has(node.right) 
                ? balance.get(node.right) 
                : 0;

            // Add moves required for left and right subtrees
            ans += Math.abs(left_balance) + Math.abs(right_balance);

            // Calculate current node's balance: (candies - 1)
            balance.set(node, node.data + left_balance + right_balance - 1);
        }
    }

    // Return the total number of moves
    return ans;
}

// Representation of given Binary Tree
//    3
//   / \
//  0   0
const root = new Node(3);
root.left = new Node(0);
root.right = new Node(0);

console.log(distributeCandy(root));

Output
2

Distribute candies in a binary tree | DSA Problem
Article Tags :

Similar Reads