Find Minimum Cost for Making All Even Numbers at Same Level Equal
Last Updated :
11 Mar, 2024
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 :
- To Find the total nodes which have even values at the same level.
- 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++
#include <bits/stdc++.h>
using namespace std;
struct node {
int data;
struct node* left;
struct node* right;
};
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);
}
int findOperation(vector< int > nodes)
{
if (nodes.size() < 2)
return 0;
int sum = 0;
for ( int i = 0; i < nodes.size(); i++) {
sum += nodes[i];
}
int average = sum / nodes.size();
int ans = 0;
for ( int i = 0; i < nodes.size(); i++) {
ans += abs (average - nodes[i]);
}
return ans;
}
int findMin(node* root)
{
if (!root)
return 0;
int operationCount = 0;
queue<node*> q;
q.push(root);
while (!q.empty()) {
int n = q.size();
vector< int > nodes;
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);
}
}
operationCount += findOperation(nodes);
}
return operationCount;
}
int main()
{
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);
cout << findMin(root);
return 0;
}
|
Java
import java.util.LinkedList;
import java.util.Queue;
import java.util.Vector;
class Node {
int data;
Node left, right;
Node( int item) {
data = item;
left = right = null ;
}
}
public class MinimumCost {
static int findOperation(Vector<Integer> nodes) {
if (nodes.size() < 2 )
return 0 ;
int sum = 0 ;
for ( int i = 0 ; i < nodes.size(); i++) {
sum += nodes.get(i);
}
int average = sum / nodes.size();
int ans = 0 ;
for ( int i = 0 ; i < nodes.size(); i++) {
ans += Math.abs(average - nodes.get(i));
}
return ans;
}
static int findMin(Node root) {
if (root == null )
return 0 ;
int operationCount = 0 ;
Queue<Node> q = new LinkedList<>();
q.add(root);
while (!q.isEmpty()) {
int n = q.size();
Vector<Integer> nodes = new Vector<>();
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);
}
}
operationCount += findOperation(nodes);
}
return operationCount;
}
public static void main(String[] args) {
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 );
System.out.println(findMin(root));
}
}
|
Python3
from collections import deque
class Node:
def __init__( self , key):
self .data = key
self .left = None
self .right = None
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
operation_count = 0
q = deque()
q.append(root)
while q:
n = len (q)
nodes = []
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)
operation_count + = find_operation(nodes)
return operation_count
if __name__ = = "__main__" :
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 )
print (find_min(root))
|
C#
using System;
using System.Collections.Generic;
class Node
{
public int data;
public Node left, right;
public Node( int item)
{
data = item;
left = right = null ;
}
}
class MinimumCost
{
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;
int operationCount = 0;
Queue<Node> q = new Queue<Node>();
q.Enqueue(root);
while (q.Count > 0)
{
int n = q.Count;
List< int > nodes = new List< int >();
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);
}
}
operationCount += FindOperation(nodes);
}
return operationCount;
}
static void Main()
{
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);
Console.WriteLine(FindMin(root));
}
}
|
Javascript
class Node {
constructor(key) {
this .data = key;
this .left = null ;
this .right = null ;
}
}
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;
}
let operationCount = 0;
const queue = [root];
while (queue.length > 0) {
const n = queue.length;
const nodes = [];
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);
}
}
operationCount += findOperation(nodes);
}
return operationCount;
}
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);
console.log(findMin(root));
|
Output
18
Time Complexity : O(N)
Auxiliary Space : O((2*height of binary tree)-1)
Share your thoughts in the comments
Please Login to comment...