Possible number of Trees having N vertex - GeeksforGeeks

17 May, 2021
Given an array arr[] of N positive integers. The task is to find the number of trees possible having N vertices such that the distance between vertex 1 and vertex i is arr[i]. The total number of such trees can be very large so return the answer with modulo 109 + 7.
Examples:
Input: arr[] = {0, 1, 1, 2}Output: 2Explanation: Below is the tree:
Input: arr[] = { 0, 3, 2, 1, 2, 2, 1 }Output: 24
Naive Approach: Below are the steps:
If A1 !=0 and if element from A2 . . . AN is 0 then the tree will not be able to be made so in this case, the count of trees will be 0.If we take the first node as root node then all nodes on level 1 must be a child of the root node and all nodes on level 2 must be a child of 1 level nodes, so there is only one possibility to place them in level-wise.Now let x be the number of nodes on ith level and y is the number of nodes on (i + 1)th level so the number of possibilities of arranging nodes on level i and (i + 1) is xy.Hence, the count of trees will be  Xi X(i + 1) where Xi Is the number of nodes in ith level.
If A1 !=0 and if element from A2 . . . AN is 0 then the tree will not be able to be made so in this case, the count of trees will be 0.
If we take the first node as root node then all nodes on level 1 must be a child of the root node and all nodes on level 2 must be a child of 1 level nodes, so there is only one possibility to place them in level-wise.
Now let x be the number of nodes on ith level and y is the number of nodes on (i + 1)th level so the number of possibilities of arranging nodes on level i and (i + 1) is xy.
Hence, the count of trees will be  Xi X(i + 1) where Xi Is the number of nodes in ith level.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach#include <bits/stdc++.h>using namespace std;const int mod = 1e9 + 7; // Function to count the total number// of trees possibleint NumberOfTrees(int arr[], int N){    // Find the max element in the    // given array    int maxElement = *max_element(arr, arr + N);     // Level array store the number of    // nodes on level i initially all    // values are zero    int level[maxElement + 1] = { 0 };    for (int i = 0; i < N; i++) {         level[arr[i]]++;    }     // In this case tree can not be created    if (arr[0] != 0 || level[0] != 1) {         return 0;    }     // To store the count of trees    int ans = 1;     // Iterate until maxElement    for (int i = 0; i < maxElement; i++) {         // Calculate level[i]^level[i+1]        for (int j = 0; j < level[i + 1]; j++) {             // Update the count of tree            ans = (ans * level[i]) % mod;        }    }     // Return the final count of trees    return ans;} // Driver Codeint main(){    int N = 7;     // Given array arr[]    int arr[] = { 0, 3, 2, 1, 2, 2, 1 };     // Function Call    cout << NumberOfTrees(arr, N);    return 0;}
// Java program for the above approachimport java.util.*; class GFG{     static int mod = (int)(1e9 + 7); // Function to count the total number// of trees possiblestatic int NumberOfTrees(int arr[], int N){         // Find the max element in the    // given array    int maxElement = Arrays.stream(arr).max().getAsInt();     // Level array store the number of    // nodes on level i initially all    // values are zero    int level[] = new int[maxElement + 1];    for(int i = 0; i < N; i++)    {        level[arr[i]]++;    }     // In this case tree can not be created    if (arr[0] != 0 || level[0] != 1)    {        return 0;    }     // To store the count of trees    int ans = 1;     // Iterate until maxElement    for(int i = 0; i < maxElement; i++)    {                 // Calculate level[i]^level[i+1]        for (int j = 0; j < level[i + 1]; j++)        {                         // Update the count of tree            ans = (ans * level[i]) % mod;        }    }     // Return the final count of trees    return ans;} // Driver Codepublic static void main(String[] args){    int N = 7;     // Given array arr[]    int arr[] = { 0, 3, 2, 1, 2, 2, 1 };     // Function call    System.out.print(NumberOfTrees(arr, N));}} // This code is contributed by Amit Katiyar
# Python3 program for the above approachmod = int(1e9 + 7) # Function to count the total number# of trees possibledef NumberOfTrees(arr, N):         # Find the max element in the    # given array    maxElement = max(arr);     # Level array store the number of    # Nodes on level i initially all    # values are zero    level = [0] * (maxElement + 1);    for i in range(N):        level[arr[i]] += 1;     # In this case tree can not be created    if (arr[0] != 0 or level[0] != 1):        return 0;     # To store the count of trees    ans = 1;     # Iterate until maxElement    for i in range(maxElement):         # Calculate level[i]^level[i+1]        for j in range(level[i + 1]):                         # Update the count of tree            ans = (ans * level[i]) % mod;     # Return the final count of trees    return ans; # Driver Codeif __name__ == '__main__':         N = 7;     # Given array arr    arr = [ 0, 3, 2, 1, 2, 2, 1 ];     # Function call    print(NumberOfTrees(arr, N)); # This code is contributed by shikhasingrajput
// C# program for the above approachusing System;using System.Linq;class GFG{     static int mod = (int)(1e9 + 7); // Function to count the total number// of trees possiblestatic int NumberOfTrees(int []arr, int N){         // Find the max element in the    // given array    int maxElement = arr.Max();     // Level array store the number of    // nodes on level i initially all    // values are zero    int []level = new int[maxElement + 1];    for(int i = 0; i < N; i++)    {        level[arr[i]]++;    }     // In this case tree can not be created    if (arr[0] != 0 || level[0] != 1)    {        return 0;    }     // To store the count of trees    int ans = 1;     // Iterate until maxElement    for(int i = 0; i < maxElement; i++)    {                 // Calculate level[i]^level[i+1]        for (int j = 0; j < level[i + 1]; j++)        {                         // Update the count of tree            ans = (ans * level[i]) % mod;        }    }     // Return the readonly count of trees    return ans;} // Driver Codepublic static void Main(String[] args){    int N = 7;     // Given array []arr    int []arr = { 0, 3, 2, 1, 2, 2, 1 };     // Function call    Console.Write(NumberOfTrees(arr, N));}} // This code is contributed by gauravrajput1
<script>// JavaScript program for the// above approach let mod = (1e9 + 7);   // Function to count the total number// of trees possiblefunction NumberOfTrees(arr, N){           // Find the max element in the    // given array    let maxElement = Math.max(...arr);       // Level array store the number of    // nodes on level i initially all    // values are zero    let level = Array.from({length: maxElement + 1}, (_, i) => 0);    for(let i = 0; i < N; i++)    {        level[arr[i]]++;    }       // In this case tree can not be created    if (arr[0] != 0 || level[0] != 1)    {        return 0;    }       // To store the count of trees    let ans = 1;       // Iterate until maxElement    for(let i = 0; i < maxElement; i++)    {                   // Calculate level[i]^level[i+1]        for (let j = 0; j < level[i + 1]; j++)        {                           // Update the count of tree            ans = (ans * level[i]) % mod;        }    }       // Return the final count of trees    return ans;}// Driver Code     let N = 7;       // Given array arr[]    let arr = [ 0, 3, 2, 1, 2, 2, 1 ];       // Function call    document.write(NumberOfTrees(arr, N)); </script>
  
24
 
Time Complexity: O(N*K) where K is the number of vertices in a level.Auxiliary Space: O(N)
 
Efficient Approach: The above approach can be optimized by optimizing the value of (ans*level[i]) using Modular Exponentiation. Below are the steps:
 
If the exponent is odd, make it even by subtracting 1 from it and multiply the base with the answer.If the exponent is even, divide the exponent by 2 and square the base.Return 1 when the exponent becomes 0.
If the exponent is odd, make it even by subtracting 1 from it and multiply the base with the answer.
If the exponent is even, divide the exponent by 2 and square the base.
Return 1 when the exponent becomes 0.
 
Below is the implementation of the above approach:
 
C++
Java
Python3
C#
Javascript
// C++ program for the above approach#include <bits/stdc++.h>using namespace std;const int mod = 1e9 + 7; // Function that finds the value of x^y// using Modular Exponentiationint power(int x, int y){    // Base Case    if (y == 0)        return 1;     int p = power(x, y / 2) % mod;     p = (p * p) % mod;     // If y is odd, multiply    // x with result    if (y & 1)        p = (x * p) % mod;     // Return the value    return p;} // Function that counts the total// number of trees possibleint NumberOfTrees(int arr[], int N){     // Find the max element in array    int maxElement        = *max_element(arr, arr + N);     // Level array store the number nodes    // on level i initially all values are 0    int level[maxElement + 1] = { 0 };     for (int i = 0; i < N; i++) {        level[arr[i]]++;    }     // In this case tree can not be created    if (arr[0] != 0 || level[0] != 1) {         return 0;    }     int ans = 1;     for (int i = 0; i < maxElement; i++) {         // Calculate level[i]^level[i+1]        ans = (ans * power(level[i],                           level[i + 1]))              % mod;    }     // Return the final count    return ans;} // Driver Codeint main(){    int N = 7;     // Given array arr[]    int arr[] = { 0, 3, 2, 1, 2, 2, 1 };     // Function Call    cout << NumberOfTrees(arr, N);    return 0;}
// Java program for the above approachimport java.util.*; class GFG{     static int mod = (int)1e9 + 7; // Function that finds the value of x^y// using Modular Exponentiationstatic int power(int x, int y){         // Base Case    if (y == 0)        return 1;     int p = power(x, y / 2) % mod;     p = (p * p) % mod;     // If y is odd, multiply    // x with result    if ((y & 1) != 0)        p = (x * p) % mod;     // Return the value    return p;} // Function that counts the total// number of trees possiblestatic int NumberOfTrees(int arr[], int N){     // Find the max element in array    int maxElement = Arrays.stream(arr).max().getAsInt();     // Level array store the number nodes    // on level i initially all values are 0    int []level = new int[maxElement + 1];     for(int i = 0; i < N; i++)    {        level[arr[i]]++;    }     // In this case tree can not be created    if (arr[0] != 0 || level[0] != 1)    {        return 0;    }         int ans = 1;     for(int i = 0; i < maxElement; i++)    {        // Calculate level[i]^level[i+1]        ans = (ans * power(level[i],                           level[i + 1])) % mod;    }     // Return the final count    return ans;} // Driver Codepublic static void main(String[] args){    int N = 7;     // Given array arr[]    int arr[] = { 0, 3, 2, 1, 2, 2, 1 };     // Function call    System.out.print(NumberOfTrees(arr, N));}} // This code is contributed by 29AjayKumar
# Python3 program for the above approachmod = int(1e9 + 7) # Function that finds the value of x^y# using Modular Exponentiationdef power(x, y):     # Base Case    if(y == 0):        return 1     p = power(x, y // 2) % mod     p = (p * p) % mod     # If y is odd, multiply    # x with result    if(y & 1):        p = (x * p) % mod     # Return the value    return p # Function that counts the total# number of trees possibledef NumberOfTrees(arr, N):     # Find the max element in array    maxElement = max(arr)     # Level array store the number nodes    # on level i initially all values are 0    level = [0] * (maxElement + 1)     for i in range(N):        level[arr[i]] += 1     # In this case tree can not be created    if(arr[0] != 0 or level[0] != 1):        return 0     ans = 1     for i in range(maxElement):         # Calculate level[i]^level[i+1]        ans = (ans * power(level[i],                           level[i + 1])) % mod     # Return the final count    return ans # Driver CodeN = 7 # Given Queriesarr = [ 0, 3, 2, 1, 2, 2, 1 ] # Function callprint(NumberOfTrees(arr, N)) # This code is contributed by Shivam Singh
// C# program for the above approachusing System;using System.Linq; class GFG{     static int mod = (int)1e9 + 7; // Function that finds the value of x^y// using Modular Exponentiationstatic int power(int x, int y){         // Base Case    if (y == 0)        return 1;     int p = power(x, y / 2) % mod;     p = (p * p) % mod;     // If y is odd, multiply    // x with result    if ((y & 1) != 0)        p = (x * p) % mod;     // Return the value    return p;} // Function that counts the total// number of trees possiblestatic int NumberOfTrees(int []arr, int N){     // Find the max element in array    int maxElement = arr.Max();     // Level array store the number nodes    // on level i initially all values are 0    int []level = new int[maxElement + 1];     for(int i = 0; i < N; i++)    {        level[arr[i]]++;    }     // In this case tree can not be created    if (arr[0] != 0 || level[0] != 1)    {        return 0;    }         int ans = 1;     for(int i = 0; i < maxElement; i++)    {                 // Calculate level[i]^level[i+1]        ans = (ans * power(level[i],                           level[i + 1])) % mod;    }     // Return the readonly count    return ans;} // Driver Codepublic static void Main(String[] args){    int N = 7;     // Given array []arr    int []arr = { 0, 3, 2, 1, 2, 2, 1 };     // Function call    Console.Write(NumberOfTrees(arr, N));}} // This code is contributed by 29AjayKumar
<script>// javascript program for the// above approach let mod = 1e9 + 7;  // Function that finds the value of x^y// using Modular Exponentiationfunction power(x, y){          // Base Case    if (y == 0)        return 1;      let p = power(x, y / 2) % mod;      p = (p * p) % mod;      // If y is odd, multiply    // x with result    if ((y & 1) != 0)        p = (x * p) % mod;      // Return the value    return p;}  // Function that counts the total// number of trees possiblefunction NumberOfTrees(arr, N){      // Find the max element in array    let maxElement = Math.max(...arr);      // Level array store the number nodes    // on level i initially all values are 0    let level = Array(maxElement + 1).fill(0);      for(let i = 0; i < N; i++)    {        level[arr[i]]++;    }      // In this case tree can not be created    if (arr[0] != 0 || level[0] != 1)    {        return 0;    }          let ans = 1;      for(let i = 0; i < maxElement; i++)    {        // Calculate level[i]^level[i+1]        ans = (ans * power(level[i],                           level[i + 1])) % mod;    }      // Return the final count    return ans;}  // Driver Code     let N = 7;      // Given array arr[]    let arr = [ 0, 3, 2, 1, 2, 2, 1 ];      // Function call    document.write(NumberOfTrees(arr, N));       // This code is contributed by decode2207.</script>
24
Time Complexity: O(N*log K) where K is the number of vertices in a level.Auxiliary Space: O(N)
SHIVAMSINGH67
amit143katiyar
GauravRajput1
29AjayKumar
shikhasingrajput
susmitakundugoaldanga
target_2
Modular Arithmetic
Permutation and Combination
Combinatorial
Greedy
Mathematical
Tree
Greedy
Mathematical
Combinatorial
Tree
Modular Arithmetic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Combinational Sum
Count ways to reach the nth stair using step 1, 2 or 3
Count of subsets with sum equal to X
Print all subsets of given size of a set
Python program to get all subsets of given size of a set
Dijkstra's shortest path algorithm | Greedy Algo-7
Program for array rotation
Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5
Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2
Huffman Coding | Greedy Algo-3