Question:
How to distribute candies in a binary tree using C++

Summary

Consider here, we have to figure out the minimum number of moves required where every node has exactly one candy. 


Let’s assume:

Method- solve and distributeCandy


Solution


//User function Template for C++


/*

struct Node {

int key;

Node *left, *right;

};

*/


class Solution{

    public:

    // int moves = 0;

    

    // int solve(Node* root){

        

    //     if(root==NULL) return 0;

        

    //     int left = solve(root->left);

    //     int right = solve(root->right);

        

    //     int k =  left + right;

        

    //     int reqMove = root->key + k - 1; 

        

    //     moves+= abs(reqMove);

        

    //     return reqMove;

    // }


    // int distributeCandy(Node* root){

        

    //     if(root==NULL) return 0;

        

    //     int n = solve(root);

    //     return moves;

    // }

    

     int solve(Node* root, int &moves){

        if(root == NULL)

        {

            return 0;

        }

        

        int left = solve(root -> left, moves);

        int right = solve(root -> right, moves);

        

        moves = moves + abs(left) + abs(right);

        

        return root->key  -1 + left + right;

    }

    int distributeCandy(Node* root) {

        int moves = 0;

        solve(root, moves);

        return moves;

    }

};


Answered by: >shreyansho85v

Credit:> >GeekforGeeks


Suggested blogs:

>How to configure python in jmeter?

>How to mock a constant value in Python?

>Creating a pivot table by 6 month interval rather than year

>How to Install mariaDB client efficiently inside docker?

>Can I call an API to find out the random seed in Python `hash()` function?

>How remove residual lines after merge two regions using Geopandas in python?


Submit
0 Answers