Open In App

Find Minimum Cost for Making All Even Numbers at Same Level Equal

Last Updated : 11 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Given a binary tree, the task is to find the minimum number of operations required to make all nodes with even numbers that are at the same level equal. You can either increment the value of the node by 1 or decrease the value by 1, this will cost you 1 operation.

Examples

Input :

                     6
                /          \
           4                2
     /       \          /       \
14           10    6        2

Output : 18

Explaination :

At level 2, there are two even numbers 4 and 2 so number of operations to make them equal will be 2.

At level 3, there are four even numbers 14, 10, 6 and 2 so for making them equal we will convert all elements to 6 and this will cost total 16 operations.

Total number of operations = 2 + 16 = 18.

Input :

                    6
              /         \
         1                 2
    /     \           /
3         10    6

Output : 4

Explaination :

There is only 1 element at level 1.

At level 2, there is only 1 even number .

At level 3, there are 2 even numbers 10 and 6 . Either of these numbers can be converted into another number at this will cost 4 operations.

So answer will be 4 here.

Approach

The problem can be broken down into two parts :

  1. To Find the total nodes which have even values at the same level.
  2. Find minimum number of operations required to make the extracted nodes equal.

This can be done by doing the below mentioned steps :

  • Start level order traversal of the binary tree and Initialize a variable operationCount with 0.
  • Traverse over the level and if the current node’s value is even then push it into a vector and after completing the level pass this vector to findOperation function and add the returned answer to operationCount variable.
  • Keep repeating this process for rest of the levels.
    • For findOperation function, if the size of vector is greater than 1 then traverse over the integer vector and store sum for calculating average and then traverse over the vector again and calculate the absolute difference of vector elements and average value in ans variable and then return ans .If size of vector is smaller than 2 then return 0.

Implementation

C++ Program to Find the Minimum Cost for Making All Even Numbers at Same Level Equal

C++




// C++ Program to Find the Minimum Cost for Making All Even
// Numbers at Same Level Equal
 
#include <bits/stdc++.h>
using namespace std;
 
// Binary tree node
struct node {
    int data;
    struct node* left;
    struct node* right;
};
 
// Function for allocating a new node
// with the given data and NULL left and right
// pointers.
struct node* newNode(int data)
{
    struct node* node
        = (struct node*)malloc(sizeof(struct node));
    node->data = data;
    node->left = NULL;
    node->right = NULL;
    return (node);
}
 
// Function that calculates minimum number
// of operations required to make all elements
// equal and return the answer
int findOperation(vector<int> nodes)
{
    if (nodes.size() < 2)
        return 0; // if node vector contains less than 2
                  // nodes then we don't have to make them
                  // equal
    int sum = 0;
    for (int i = 0; i < nodes.size(); i++) {
        sum += nodes[i]; // adding sum
    }
    int average = sum / nodes.size(); // calculating average
    // In ans variable calculated the difference
    // between nodes values and the average
    int ans = 0;
    for (int i = 0; i < nodes.size(); i++) {
        ans += abs(average - nodes[i]);
    }
 
    // This ans will be the minimum number of
    // operations that will be required to
    // make every element equal
    return ans;
}
 
int findMin(node* root)
{
    if (!root)
        return 0;
 
    // Variable for storing the number
    // of operations
    int operationCount = 0;
 
    // Queue for level order traversal
    queue<node*> q;
    q.push(root);
 
    // Level order traversal
    while (!q.empty()) {
 
        // Finding the number of nodes in
        // current level
        int n = q.size();
 
        // Vector to store values of
        // even nodes at current level
        vector<int> nodes;
 
        // Traversing over the current level
        for (int i = 0; i < n; i++) {
            node* temp = q.front();
            q.pop();
            if (temp->left != NULL)
                q.push(temp->left);
            if (temp->right != NULL)
                q.push(temp->right);
            if (temp->data % 2 == 0) {
                nodes.push_back(temp->data);
            }
        }
 
        // Call the minOperation
        // function for all even nodes in
        // current level and add the
        // answer to operationCount
        operationCount += findOperation(nodes);
    }
 
    // After traversing all the levels return
    // the operationCount variable
    return operationCount;
}
 
// Driver code
int main()
{
 
    // Initializing the tree
    struct node* root = newNode(6);
    root->left = newNode(4);
    root->right = newNode(2);
    root->left->left = newNode(14);
    root->right->left = newNode(10);
    root->right->right = newNode(6);
    root->left->right = newNode(2);
 
    // Function call
    cout << findMin(root);
 
    return 0;
}


Java




/*code contributed by Flutterfly*/
import java.util.LinkedList;
import java.util.Queue;
import java.util.Vector;
 
// Binary tree node
class Node {
    int data;
    Node left, right;
 
    // Constructor to create a new node with the given data
    Node(int item) {
        data = item;
        left = right = null;
    }
}
 
public class MinimumCost {
 
    // Function to calculate the minimum number of operations required
    // to make all elements equal and return the answer
    static int findOperation(Vector<Integer> nodes) {
        if (nodes.size() < 2)
            return 0; // If the node vector contains less than 2 nodes, no need to make them equal
 
        int sum = 0;
        for (int i = 0; i < nodes.size(); i++) {
            sum += nodes.get(i); // Adding sum
        }
        int average = sum / nodes.size(); // Calculating average
 
        // In ans variable, calculate the difference between node values and the average
        int ans = 0;
        for (int i = 0; i < nodes.size(); i++) {
            ans += Math.abs(average - nodes.get(i));
        }
 
        // This ans will be the minimum number of operations required
        // to make every element equal
        return ans;
    }
 
    static int findMin(Node root) {
        if (root == null)
            return 0;
 
        // Variable for storing the number of operations
        int operationCount = 0;
 
        // Queue for level order traversal
        Queue<Node> q = new LinkedList<>();
        q.add(root);
 
        // Level order traversal
        while (!q.isEmpty()) {
 
            // Finding the number of nodes in the current level
            int n = q.size();
 
            // Vector to store values of even nodes at the current level
            Vector<Integer> nodes = new Vector<>();
 
            // Traversing over the current level
            for (int i = 0; i < n; i++) {
                Node temp = q.poll();
                if (temp.left != null)
                    q.add(temp.left);
                if (temp.right != null)
                    q.add(temp.right);
                if (temp.data % 2 == 0) {
                    nodes.add(temp.data);
                }
            }
 
            // Call the findOperation function for all even nodes in
            // the current level and add the answer to operationCount
            operationCount += findOperation(nodes);
        }
 
        // After traversing all the levels, return the operationCount variable
        return operationCount;
    }
 
    // Driver code
    public static void main(String[] args) {
 
        // Initializing the tree
        Node root = new Node(6);
        root.left = new Node(4);
        root.right = new Node(2);
        root.left.left = new Node(14);
        root.right.left = new Node(10);
        root.right.right = new Node(6);
        root.left.right = new Node(2);
 
        // Function call
        System.out.println(findMin(root));
    }
}


Python3




# code contributed by Flutterfly
from collections import deque
 
# Binary tree node
class Node:
    def __init__(self, key):
        self.data = key
        self.left = None
        self.right = None
 
# Function that calculates the minimum number
# of operations required to make all elements
# equal and returns the answer
def find_operation(nodes):
    if len(nodes) < 2:
        return 0
 
    total_sum = sum(nodes)
    average = total_sum // len(nodes)
 
    ans = sum(abs(average - x) for x in nodes)
    return ans
 
def find_min(root):
    if root is None:
        return 0
 
    # Variable for storing the number of operations
    operation_count = 0
 
    # Queue for level order traversal
    q = deque()
    q.append(root)
 
    # Level order traversal
    while q:
        n = len(q)
 
        # List to store values of even nodes at the current level
        nodes = []
 
        # Traversing over the current level
        for i in range(n):
            temp = q.popleft()
            if temp.left:
                q.append(temp.left)
            if temp.right:
                q.append(temp.right)
            if temp.data % 2 == 0:
                nodes.append(temp.data)
 
        # Call the find_operation function for all even nodes in
        # the current level and add the answer to operation_count
        operation_count += find_operation(nodes)
 
    # After traversing all the levels, return the operation_count variable
    return operation_count
 
# Driver code
if __name__ == "__main__":
    # Initializing the tree
    root = Node(6)
    root.left = Node(4)
    root.right = Node(2)
    root.left.left = Node(14)
    root.right.left = Node(10)
    root.right.right = Node(6)
    root.left.right = Node(2)
 
    # Function call
    print(find_min(root))


C#




// code contributed by Flutterfly
using System;
using System.Collections.Generic;
 
// Binary tree node
class Node
{
    public int data;
    public Node left, right;
 
    // Constructor to create a new node with the given data
    public Node(int item)
    {
        data = item;
        left = right = null;
    }
}
 
class MinimumCost
{
    // Function that calculates the minimum number
    // of operations required to make all elements
    // equal and returns the answer
    static int FindOperation(List<int> nodes)
    {
        if (nodes.Count < 2)
            return 0;
 
        int sum = 0;
        foreach (var node in nodes)
        {
            sum += node;
        }
        int average = sum / nodes.Count;
 
        int ans = 0;
        foreach (var node in nodes)
        {
            ans += Math.Abs(average - node);
        }
 
        return ans;
    }
 
    static int FindMin(Node root)
    {
        if (root == null)
            return 0;
 
        // Variable for storing the number of operations
        int operationCount = 0;
 
        // Queue for level order traversal
        Queue<Node> q = new Queue<Node>();
        q.Enqueue(root);
 
        // Level order traversal
        while (q.Count > 0)
        {
            int n = q.Count;
 
            // List to store values of even nodes at the current level
            List<int> nodes = new List<int>();
 
            // Traversing over the current level
            for (int i = 0; i < n; i++)
            {
                Node temp = q.Dequeue();
                if (temp.left != null)
                    q.Enqueue(temp.left);
                if (temp.right != null)
                    q.Enqueue(temp.right);
                if (temp.data % 2 == 0)
                {
                    nodes.Add(temp.data);
                }
            }
 
            // Call the FindOperation function for all even nodes in
            // the current level and add the answer to operationCount
            operationCount += FindOperation(nodes);
        }
 
        // After traversing all the levels, return the operationCount variable
        return operationCount;
    }
 
    // Driver code
    static void Main()
    {
        // Initializing the tree
        Node root = new Node(6);
        root.left = new Node(4);
        root.right = new Node(2);
        root.left.left = new Node(14);
        root.right.left = new Node(10);
        root.right.right = new Node(6);
        root.left.right = new Node(2);
 
        // Function call
        Console.WriteLine(FindMin(root));
    }
}


Javascript




// code contributed by Flutterfly
//Binary tree node
class Node {
    constructor(key) {
        this.data = key;
        this.left = null;
        this.right = null;
    }
}
 
// Function that calculates the minimum number
// of operations required to make all elements
// equal and returns the answer
function findOperation(nodes) {
    if (nodes.length < 2) {
        return 0;
    }
 
    const sum = nodes.reduce((acc, node) => acc + node, 0);
    const average = Math.floor(sum / nodes.length);
 
    const ans = nodes.reduce((acc, node) => acc + Math.abs(average - node), 0);
    return ans;
}
 
function findMin(root) {
    if (root === null) {
        return 0;
    }
 
    // Variable for storing the number of operations
    let operationCount = 0;
 
    // Queue for level order traversal
    const queue = [root];
 
    // Level order traversal
    while (queue.length > 0) {
        const n = queue.length;
 
        // Array to store values of even nodes at the current level
        const nodes = [];
 
        // Traversing over the current level
        for (let i = 0; i < n; i++) {
            const temp = queue.shift();
            if (temp.left) {
                queue.push(temp.left);
            }
            if (temp.right) {
                queue.push(temp.right);
            }
            if (temp.data % 2 === 0) {
                nodes.push(temp.data);
            }
        }
 
        // Call the findOperation function for all even nodes in
        // the current level and add the answer to operationCount
        operationCount += findOperation(nodes);
    }
 
    // After traversing all the levels, return the operationCount variable
    return operationCount;
}
 
// Driver code
const root = new Node(6);
root.left = new Node(4);
root.right = new Node(2);
root.left.left = new Node(14);
root.right.left = new Node(10);
root.right.right = new Node(6);
root.left.right = new Node(2);
 
// Function call
console.log(findMin(root));


Output

18

Time Complexity : O(N)

Auxiliary Space : O((2*height of binary tree)-1)



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads