Given a binary tree that contains multiple nodes, the task is to find a minimum number of operations required to make leaf nodes at the same level equal. By performing one operation you can either increase the node's value by one or decrease the node's value by one.
Examples:
Input:
Output: 6 Explanation: There is no leaf node at levels 1 and 2, we have 3 leaf nodes at level 3 which have values 9, 5, and 3. To make these three equal we can reduce 9 by 4 which will cost 4 operations then second leaf node 5 will remain the same and then the third leaf node will be incremented twice which will cost 2 operations. So in the end all leaf nodes at level three will have a value of 5 and this will cost a total of 6 operations. At level 4 there is only 1 leaf node so no operations will be performed here.
Input:
Output: 2 Explanation: There are two leaf nodes at level 2 which have values 5 and 7 so we can increment 5 by 2 and this will cost us 2 operations.
Approach:
The idea is to start traversing in level order manner and find the total number of nodes which we need to make equal in the same level then after finding these nodes calculate minimum number of operations by making each element equal to average of all elements.
Below code is implementation for above approach:
C++
// C++ implementation to calculate the minimum number of operations // required to make all leaf nodes of a binary tree equal#include<bits/stdc++.h>usingnamespacestd;classNode{public:intdata;Node*left;Node*right;Node(intx){data=x;left=right=nullptr;}};// Function that returns true if current node// is leaf otherwise falseboolisLeaf(Node*root){if(root->left==NULL&&root->right==NULL)returntrue;returnfalse;}// Function that calculates minimum number// of operations required to make all elements// of array equal and return that valueintfindMinOperation(vector<int>&leafs){intval=leafs[0];// Running for loop for calculating the// average of all numbers present in arrayfor(inti=1;i<leafs.size();i++){val=(val+leafs[i])/2;}// So the number calculated as average is// the number which will be lead to// minimum operationintans=0;for(inti=0;i<leafs.size();i++){ans+=abs(val-leafs[i]);}// This ans will be the minimum number of// operations which will be required to// make every element equalreturnans;}intminimumOperation(Node*root){if(!root)return0;intminOperation=0;queue<Node*>q;q.push(root);while(!q.empty()){intn=q.size();vector<int>leafs;// Traversing over the current levelfor(inti=0;i<n;i++){Node*curr=q.front();q.pop();if(curr->left!=NULL)q.push(curr->left);if(curr->right!=NULL)q.push(curr->right);// If current node is a leaf// node then push its value in// leafs vectorif(isLeaf(curr))leafs.push_back(curr->data);}// If there are more than 1 leaf node in// current level than for making them// equal we will calculate minoperationif(leafs.size()>1){minOperation+=findMinOperation(leafs);}}returnminOperation;}intmain(){// Initializing the tree// 6// / \ // 4 2// / \ / \ // 1 9 5 3// /// 10Node*root=newNode(6);root->left=newNode(4);root->right=newNode(2);root->left->left=newNode(1);root->left->right=newNode(9);root->right->left=newNode(5);root->right->right=newNode(3);root->left->left->right=newNode(10);cout<<minimumOperation(root);return0;}
Java
// Java implementation to calculate the minimum number of operations // required to make all leaf nodes of a binary tree equalimportjava.util.*;classNode{intdata;Nodeleft,right;Node(intx){data=x;left=right=null;}}classGfG{// Function that returns true if current node// is leaf otherwise falsestaticbooleanisLeaf(Noderoot){return(root.left==null&&root.right==null);}// Function that calculates minimum number of operations required // to make all elements of array equal and return that valuestaticintfindMinOperation(int[]leafs){intval=leafs[0];// Running for loop for calculating the average // of all numbers present in arrayfor(inti=1;i<leafs.length;i++){val=(val+leafs[i])/2;}// So the number calculated as average is the number// which will lead to minimum operationintans=0;for(inti=0;i<leafs.length;i++){ans+=Math.abs(val-leafs[i]);}// This ans will be the minimum number of operations // which will be required to make every element equalreturnans;}staticintminimumOperation(Noderoot){if(root==null)return0;intminOperation=0;Queue<Node>q=newLinkedList<>();q.add(root);while(!q.isEmpty()){intn=q.size();List<Integer>leafs=newArrayList<>();// Traversing over the current levelfor(inti=0;i<n;i++){Nodecurr=q.poll();if(curr.left!=null)q.add(curr.left);if(curr.right!=null)q.add(curr.right);// If current node is a leaf node then// push its value in leafs vectorif(isLeaf(curr))leafs.add(curr.data);}// If there are more than 1 leaf node in// current level than for making them equal// we will calculate minoperationif(leafs.size()>1){int[]leafsArray=leafs.stream().mapToInt(i->i).toArray();minOperation+=findMinOperation(leafsArray);}}returnminOperation;}publicstaticvoidmain(String[]args){// Initializing the tree// 6// / \// 4 2// / \ / \// 1 9 5 3// /// 10Noderoot=newNode(6);root.left=newNode(4);root.right=newNode(2);root.left.left=newNode(1);root.left.right=newNode(9);root.right.left=newNode(5);root.right.right=newNode(3);root.left.left.right=newNode(10);System.out.println(minimumOperation(root));}}
Python
# Python implementation to calculate the minimum number of operations # required to make all leaf nodes of a binary tree equalclassNode:def__init__(self,x):self.data=xself.left=Noneself.right=Nonedefis_leaf(root):returnroot.leftisNoneandroot.rightisNonedeffind_min_operation(leafs):val=leafs[0]# Running for loop for calculating the average# of all numbers present in arrayforiinrange(1,len(leafs)):val=(val+leafs[i])//2# So the number calculated as average is the number# which will lead to minimum operationans=sum(abs(val-leaf)forleafinleafs)# This ans will be the minimum number of operations# which will be required to make every element equalreturnansdefminimum_operation(root):ifnotroot:return0min_operation=0q=[root]whileq:n=len(q)leafs=[]for_inrange(n):curr=q.pop(0)ifcurr.left:q.append(curr.left)ifcurr.right:q.append(curr.right)# If current node is a leaf node# then push its value in leafs vectorifis_leaf(curr):leafs.append(curr.data)iflen(leafs)>1:min_operation+=find_min_operation(leafs)returnmin_operation# Initializing the tree# 6# / \# 4 2# / \ / \# 1 9 5 3# /# 10root=Node(6)root.left=Node(4)root.right=Node(2)root.left.left=Node(1)root.left.right=Node(9)root.right.left=Node(5)root.right.right=Node(3)root.left.left.right=Node(10)print(minimum_operation(root))
C#
// C# implementation to calculate the minimum number of operations // required to make all leaf nodes of a binary tree equalusingSystem;usingSystem.Collections.Generic;classNode{publicintdata;publicNodeleft,right;publicNode(intx){data=x;left=right=null;}}classGfG{staticboolIsLeaf(Noderoot){return(root.left==null&&root.right==null);}// Function that calculates minimum number of operations required // to make all elements of array equal and return that valuestaticintFindMinOperation(List<int>leafs){intval=leafs[0];// Running for loop for calculating the average// of all numbers present in arrayfor(inti=1;i<leafs.Count;i++){val=(val+leafs[i])/2;}// So the number calculated as average is the number // which will lead to minimum operationintans=0;for(inti=0;i<leafs.Count;i++){ans+=Math.Abs(val-leafs[i]);}// This ans will be the minimum number of operations // which will be required to make every element equalreturnans;}staticintMinimumOperation(Noderoot){if(root==null)return0;intminOperation=0;Queue<Node>q=newQueue<Node>();q.Enqueue(root);while(q.Count>0){intn=q.Count;List<int>leafs=newList<int>();// Traversing over the current levelfor(inti=0;i<n;i++){Nodecurr=q.Dequeue();if(curr.left!=null)q.Enqueue(curr.left);if(curr.right!=null)q.Enqueue(curr.right);// If current node is a leaf node then// push its value in leafs vectorif(IsLeaf(curr))leafs.Add(curr.data);}if(leafs.Count>1){minOperation+=FindMinOperation(leafs);}}returnminOperation;}staticvoidMain(string[]args){// Initializing the tree// 6// / \// 4 2// / \ / \// 1 9 5 3// /// 10Noderoot=newNode(6);root.left=newNode(4);root.right=newNode(2);root.left.left=newNode(1);root.left.right=newNode(9);root.right.left=newNode(5);root.right.right=newNode(3);root.left.left.right=newNode(10);Console.WriteLine(MinimumOperation(root));}}
JavaScript
// JavaScript implementation to calculate the// minimum number of operations required to make all // leaf nodes of a binary tree equalclassNode{constructor(x){this.data=x;this.left=this.right=null;}}functionisLeaf(root){returnroot.left===null&&root.right===null;}functionfindMinOperation(leafs){letval=leafs[0];// Running for loop for calculating the average // of all numbers present in arrayfor(leti=1;i<leafs.length;i++){val=Math.floor((val+leafs[i])/2);}// So the number calculated as average is the number // which will lead to minimum operationletans=0;for(leti=0;i<leafs.length;i++){ans+=Math.abs(val-leafs[i]);}// This ans will be the minimum number of operations // which will be required to make every element equalreturnans;}functionminimumOperation(root){if(!root)return0;letminOperation=0;letq=[root];while(q.length>0){letn=q.length;letleafs=[];for(leti=0;i<n;i++){letcurr=q.shift();if(curr.left)q.push(curr.left);if(curr.right)q.push(curr.right);if(isLeaf(curr))leafs.push(curr.data);}if(leafs.length>1){minOperation+=findMinOperation(leafs);}}returnminOperation;}// Initializing the tree// 6// / \// 4 2// / \ / \// 1 9 5 3// /// 10letroot=newNode(6);root.left=newNode(4);root.right=newNode(2);root.left.left=newNode(1);root.left.right=newNode(9);root.right.left=newNode(5);root.right.right=newNode(3);root.left.left.right=newNode(10);console.log(minimumOperation(root));
Output
6
Time Complexity: O(n), where n is the number of nodes in tree. Auxillary space: O(n).