📌  相关文章
📜  完整二叉树的最小数量,以使叶子的数量为N

📅  最后修改于: 2021-05-25 00:54:19             🧑  作者: Mango

给定一个整数N和无限个不同深度的完整二叉树,任务是选择最小数量的树,以使每棵树中的叶节点总数为N。

例子:

方法:由于完整的二叉树中叶节点的数量始终是2的幂。因此,现在问题被简化为寻找2的幂,当将它们相加时会得到N,以使总和中的项总数最小,这是所需的答案。
由于2的每个幂在其二进制表示中仅包含一个’1’,因此N将包含与总和中的项数相同数量的’1’(假设我们采用最少的项数)。因此,问题进一步减少为找到N中的设置位数,使用本文中使用的方法可以很容易地计算出该位数。

下面是上述方法的实现:

C++
// C++ implementation of the approach
#include 
using namespace std;
  
// Function to return the minimum
// count of trees required
int minTrees(int n)
{
  
    // To store the count of
    // set bits in n
    int count = 0;
  
    while (n) {
        n &= (n - 1);
        count++;
    }
    return count;
}
  
// Driver code
int main()
{
    int n = 7;
  
    cout << minTrees(n);
  
    return 0;
}


Java
// Java implementation of the approach
class GFG
{
  
// Function to return the minimum
// count of trees required
static int minTrees(int n)
{
  
    // To store the count of
    // set bits in n
    int count = 0;
  
    while (n > 0)
    {
        n &= (n - 1);
        count++;
    }
    return count;
}
  
// Driver code
public static void main(String[] args)
{
    int n = 7;
  
    System.out.print(minTrees(n));
}
}
  
// This code is contributed by 29AjayKumar


Python3
# Python3 implementation of the approach
  
# Function to return the minimum
# count of trees required
def minTrees(n):
  
    # To store the count of
    # set bits in n
    count = 0;
  
    while (n):
        n &= (n - 1);
        count += 1;
    return count;
  
# Driver code
if __name__ == '__main__':
    n = 7;
    print(minTrees(n));
  
# This code is contributed by 29AjayKumar


C#
// C# implementation of the approach
using System;
  
class GFG
{
  
    // Function to return the minimum
    // count of trees required
    static int minTrees(int n)
    {
      
        // To store the count of
        // set bits in n
        int count = 0;
      
        while (n > 0)
        {
            n &= (n - 1);
            count++;
        }
        return count;
    }
      
    // Driver code
    public static void Main()
    {
        int n = 7;
      
        Console.Write(minTrees(n));
    }
}
  
// This code is contributed by AnkitRai01


输出:
3