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.
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.
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:
Output
6
Time Complexity: O(n), where n is the number of nodes in tree. Auxillary space: O(n).