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++

 `// 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

 ``

Output:

`14`

Time Complexity: O(log n)

Auxiliary Space: O(1)