Number of edges in a perfect binary tree with N levels
Last Updated :
10 Mar, 2022
Given a positive integer N, the task is to find the count of edges of a perfect binary tree with N levels.
Examples:
Input: N = 2
Output: 2
1
/ \
2 3
Input: N = 3
Output: 6
1
/ \
2 3
/ \ / \
4 5 6 7
Approach: It can be observed that for the values of N = 1, 2, 3, …, a series will be formed as 0, 2, 6, 14, 30, 62, … whose Nth term is 2N – 2.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int cntEdges( int n)
{
int edges = pow (2, n) - 2;
return edges;
}
int main()
{
int n = 4;
cout << cntEdges(n);
return 0;
}
|
Java
class GFG
{
static int cntEdges( int n)
{
int edges = ( int )Math.pow( 2 , n) - 2 ;
return edges;
}
public static void main(String[] args)
{
int n = 4 ;
System.out.println(cntEdges(n));
}
}
|
Python3
def cntEdges(n) :
edges = 2 * * n - 2 ;
return edges;
if __name__ = = "__main__" :
n = 4 ;
print (cntEdges(n));
|
C#
using System;
class GFG
{
static int cntEdges( int n)
{
int edges = ( int )Math.Pow(2, n) - 2;
return edges;
}
public static void Main(String[] args)
{
int n = 4;
Console.Write(cntEdges(n));
}
}
|
Javascript
<script>
function cntEdges(n)
{
var edges = Math.pow(2, n) - 2;
return edges;
}
var n = 4;
document.write(cntEdges(n));
</script>
|
Time Complexity: O(log n)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...