Distribute Coins in Binary Tree in C++

Suppose we have the root of a binary tree with N nodes, here each node in the tree has node.val number of coins, and there are N coins in total. In one move, we can choose two adjacent nodes and move only one coin from one node to the another node. (The move may be from parent to child node, or from child to parent node.). We have to find the number of moves required to make every node have exactly one coin.

So if the tree is like −

Then the output will be 3. From the left child, send 2 coins to the root (one move for each coin, so total 2 moves), then move one coin from root to the right child, so in total there are 3 moves.

To solve this, we will follow these steps −

  • Define one recursive method called solve(), this will take a node called root

  • if root is null, then return 0

  • l := solve(left of the root)

  • r := solve(right of the root)

  • ans := |l| + |r|

  • return l + r + value of root – 1

  • in the main section, set ans := 0, call solve(root), then return ans


 Live Demo

#include <bits/stdc++.h>
using namespace std;
class TreeNode{
   int val;
   TreeNode *left, *right;
   TreeNode(int data){
      val = data;
      left = NULL;
      right = NULL;
void insert(TreeNode **root, int val){
   queue<TreeNode*> q;
      TreeNode *temp = q.front();
         if(val != NULL)
            temp->left = new TreeNode(val);
            temp->left = new TreeNode(0);
         if(val != NULL)
            temp->right = new TreeNode(val);
            temp->right = new TreeNode(0);
TreeNode *make_tree(vector<int> v){
   TreeNode *root = new TreeNode(v[0]);
   for(int i = 1; i<v.size(); i++){
      insert(&root, v[i]);
   return root;
class Solution {
   int ans;
   int solve(TreeNode* root){
      if(!root)return 0;
      int l = solve(root->left);
      int r = solve(root->right);
      ans += abs(l) + abs(r);
      return l + r + root->val - 1;
   int distributeCoins(TreeNode* root) {
      ans = 0;
      return ans;
   vector<int> v = {0,3,0};
   TreeNode *root = make_tree(v);
   Solution ob;
   cout << (ob.distributeCoins(root));