Minimum count of Full Binary Trees such that the count of leaves is N
Last Updated :
10 Jun, 2021
Given an integer N and an infinite number of Full Binary Trees of different depths, the task is to choose minimum number of trees such that the sum of the count of leaf nodes in each of the tree is N.
Example:
Input: N = 7
Output: 3
Trees with depths 2, 1 and 0 can be picked
with the number of leaf nodes as 4, 2 and 1 respectively.
(4 + 2 + 1) = 7
Input: N = 1
Output: 1
Approach: Since the number of leaf nodes in a full binary tree is always a power of two. So, the problem now gets reduced to finding the powers of 2 which give N when added together such that the total number of terms in the summation is minimum which is the required answer.
Since every power of 2 contains only one ‘1’ in its binary representation, so N will contain the same number of ‘1’s as the number of terms in summation (assuming we take the minimum number of terms). So, the problem further gets reduced to finding the number of set bits in N which can be easily calculated using the approach used in this post.
Below is the implementation of the above approach:
C++
#include <iostream>
using namespace std;
int minTrees( int n)
{
int count = 0;
while (n) {
n &= (n - 1);
count++;
}
return count;
}
int main()
{
int n = 7;
cout << minTrees(n);
return 0;
}
|
Java
class GFG
{
static int minTrees( int n)
{
int count = 0 ;
while (n > 0 )
{
n &= (n - 1 );
count++;
}
return count;
}
public static void main(String[] args)
{
int n = 7 ;
System.out.print(minTrees(n));
}
}
|
Python3
def minTrees(n):
count = 0 ;
while (n):
n & = (n - 1 );
count + = 1 ;
return count;
if __name__ = = '__main__' :
n = 7 ;
print (minTrees(n));
|
C#
using System;
class GFG
{
static int minTrees( int n)
{
int count = 0;
while (n > 0)
{
n &= (n - 1);
count++;
}
return count;
}
public static void Main()
{
int n = 7;
Console.Write(minTrees(n));
}
}
|
Javascript
<script>
function minTrees(n)
{
let count = 0;
while (n > 0)
{
n &= (n - 1);
count++;
}
return count;
}
let n = 7;
document.write(minTrees(n));
</script>
|
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...