📜  具有N个层的理想二叉树中的边数

📅  最后修改于: 2021-04-23 06:54:20             🧑  作者: Mango

给定正整数N ,任务是找到具有N个层的理想二叉树的边数。
例子:

Input: N = 2
Output: 2
  1
 / \
2   3

Input: N = 3
Output: 6
     1
   /    \
  2      3
 / \    /  \
4   5  6    7

方法:可以观察到,对于N = 1、2、3,…的值,将形成一个序列,分别为0、2、6、14、30、62,…,N项是2 N – 2
下面是上述方法的实现:

C++
// C++ implementation of the approach
#include 
using namespace std;
 
// Function to return the count
// of edges in an n-level
// perfect binary tree
int cntEdges(int n)
{
    int edges = pow(2, n) - 2;
    return edges;
}
 
// Driver code
int main()
{
    int n = 4;
 
    cout << cntEdges(n);
 
    return 0;
}


Java
// Java implementation of the approach
class GFG
{
     
// Function to return the count
// of edges in an n-level
// perfect binary tree
static int cntEdges(int n)
{
    int edges = (int)Math.pow(2, n) - 2;
    return edges;
}
 
// Driver code
public static void main(String[] args)
{
    int n = 4;
 
    System.out.println(cntEdges(n));
}
}
 
// This code is contributed by Code_Mech


Python3
# Python3 implementation of the approach
 
# Function to return the count
# of edges in an n-level
# perfect binary tree
def cntEdges(n) :
 
    edges = 2 ** n - 2;
     
    return edges;
 
# Driver code
if __name__ == "__main__" :
 
    n = 4;
 
    print(cntEdges(n));
 
# This code is contributed by AnkitRai01


C#
// C# implementation of the approach
using System;
class GFG
{
     
// Function to return the count
// of edges in an n-level
// perfect binary tree
static int cntEdges(int n)
{
    int edges = (int)Math.Pow(2, n) - 2;
    return edges;
}
 
// Driver code
public static void Main(String[] args)
{
    int n = 4;
 
    Console.Write(cntEdges(n));
}
}
 
// This code is contributed by Mohit Kumar


Javascript


输出:
14