Dado un entero positivo N , la tarea es encontrar el número de aristas de un árbol binario perfecto con N niveles.
Ejemplos:
Input: N = 2 Output: 2 1 / \ 2 3 Input: N = 3 Output: 6 1 / \ 2 3 / \ / \ 4 5 6 7
Planteamiento: Se puede observar que para los valores de N = 1, 2, 3,… , se formará una serie como 0, 2, 6, 14, 30, 62,… cuyo N -ésimo término es 2 N – 2 .
A continuación se muestra la implementación del enfoque anterior:
C++
// C++ implementation of the approach #include <bits/stdc++.h> 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
<script> // Javascript implementation of the approach // Function to return the count // of edges in an n-level // perfect binary tree function cntEdges(n) { var edges = Math.pow(2, n) - 2; return edges; } // Driver code var n = 4; document.write(cntEdges(n)); </script>
Producción:
14
Complejidad de tiempo: O (log n)
Espacio Auxiliar: O(1)