Open In App

Number of full binary trees such that each node is product of its children

Last Updated : 19 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given an array of n integers, each integer is greater than 1. The task is to find the number of Full binary tree from the given integers, such that each non-leaf node value is the product of its children value. Given that, each integer can be used multiple times in a full binary tree. 

Examples: 

Input : arr[] = { 2, 3, 4, 6 }.
Output : 7
There can be 7 full binary tree with the given product property.

// Four trees with single nodes
2  3  4  6

// Three trees with three nodes
  4   ,
 / \
2   2

  6    ,
 / \
2   3

  6
 / \
3   2  

We find maximum value in given array and create an array to store presence of elements in this array. The idea is, for all multiples of each integer less than the maximum value of the array, try to make full binary tree if the multiple is present in the array. 
Observe that for any full binary tree with given property, the smaller values will always be at the last level. So, try to find the number of such full binary tree from the minimum value of the array to maximum value of the array.

Algorithm: 

  1. Initialize possible number of such full binary tree for each element equal to 1. Since single node also contribute to the answer. 
  2. For each element of the array, arr[i], from minimum value to maximum value of array. 
    1. For each multiple of arr[i], find if multiple is present or not. 
    2. If yes, then the number of such possible full binary tree for multiple of arr[i], say m, is equal to the product of the number of such possible full binary tree of arr[i] and number of such possible full binary tree of arr[i]/m. 

Implementation:

C++




// C++ program to find number of full binary tree
// such that each node is product of its children.
#include<bits/stdc++.h>
using namespace std;
  
// Return the number of all possible full binary
// tree with given product property.
int numoffbt(int arr[], int n)
{
    // Finding the minimum and maximum values in
    // given array.
    int maxvalue = INT_MIN, minvalue = INT_MAX;
    for (int i = 0; i < n; i++)
    {
        maxvalue = max(maxvalue, arr[i]);
        minvalue = min(minvalue, arr[i]);
    }
  
    int mark[maxvalue + 2];
    int value[maxvalue + 2];
    memset(mark, 0, sizeof(mark));
    memset(value, 0, sizeof(value));
  
    // Marking the presence of each array element
    // and initialising the number of possible
    // full binary tree for each integer equal
    // to 1 because single node will also
    // contribute as a full binary tree.
    for (int i = 0; i < n; i++)
    {
        mark[arr[i]] = 1;
        value[arr[i]] = 1;
    }
  
    // From minimum value to maximum value of array
    // finding the number of all possible Full
    // Binary Trees.
    int ans = 0;
    for (int i = minvalue; i <= maxvalue; i++)
    {
        // Find if value present in the array
        if (mark[i])
        {
            // For each multiple of i, less than
            // equal to maximum value of array
            for (int j = i + i;
                 j <= maxvalue && j/i <= i; j += i)
            {
                // If multiple is not present in the
                // array then continue.
                if (!mark[j])
                    continue;
  
                // Finding the number of possible Full
                // binary trees for multiple j by
                // multiplying number of possible Full
                // binary tree from the number i and
                // number of possible Full binary tree
                // from i/j.
                value[j] = value[j] + (value[i] * value[j/i]);
  
                // Condition for possibility when left
                // child became right child and vice versa.
                if (i != j/i)
                    value[j] = value[j] + (value[i] * value[j/i]);
            }
        }
  
        ans += value[i];
    }
  
    return ans;
}
  
// Driven Program
int main()
{
    int arr[] = { 2, 3, 4, 6 };
    int n = sizeof(arr)/sizeof(arr[0]);
  
    cout << numoffbt(arr, n) << endl;
    return 0;
}


Java




// Java program to find number of full 
// binary tree such that each node is 
// product of its children.
import java.util.Arrays;
  
class GFG {
      
    // Return the number of all possible 
    // full binary tree with given product
    // property.
    static int numoffbt(int arr[], int n)
    {
          
        // Finding the minimum and maximum
        // values in given array.
        int maxvalue = -2147483647;
        int minvalue = 2147483647;
        for (int i = 0; i < n; i++)
        {
            maxvalue = Math.max(maxvalue, arr[i]);
            minvalue = Math.min(minvalue, arr[i]);
        }
      
        int mark[] = new int[maxvalue + 2];
        int value[] = new int[maxvalue + 2];
        Arrays.fill(mark, 0);
        Arrays.fill(value, 0);
      
        // Marking the presence of each array element
        // and initialising the number of possible
        // full binary tree for each integer equal
        // to 1 because single node will also
        // contribute as a full binary tree.
        for (int i = 0; i < n; i++)
        {
            mark[arr[i]] = 1;
            value[arr[i]] = 1;
        }
      
        // From minimum value to maximum value of array
        // finding the number of all possible Full
        // Binary Trees.
        int ans = 0;
        for (int i = minvalue; i <= maxvalue; i++)
        {
              
            // Find if value present in the array
            if (mark[i] != 0)
            {
                // For each multiple of i, less than
                // equal to maximum value of array
                for (int j = i + i;
                    j <= maxvalue && j/i <= i; j += i)
                {
                    // If multiple is not present in
                    // the array then continue.
                    if (mark[j] == 0)
                        continue;
      
                    // Finding the number of possible
                    // Full binary trees for multiple
                    // j by multiplying number of 
                    // possible Full binary tree from 
                    // the number i and number of 
                    // possible Full binary tree from i/j.
                    value[j] = value[j] + (value[i] 
                                          * value[j/i]);
      
                    // Condition for possibility when 
                    // left child became right child 
                    // and vice versa.
                    if (i != j / i)
                        value[j] = value[j] + (value[i]
                                         * value[j/i]);
                }
            }
      
            ans += value[i];
        }
      
        return ans;
    }
      
    //driver code
    public static void main (String[] args)
    {
        int arr[] = { 2, 3, 4, 6 };
        int n = arr.length;
      
        System.out.print(numoffbt(arr, n));
    }
}
  
//This code is contributed by Anant Agarwal.


Python3




   
# Python3 program to find number of
# full binary tree such that each node
# is product of its children.
  
# Return the number of all possible full 
# binary tree with given product property.
def numoffbt(arr, n):
  
    # Finding the minimum and maximum 
    # values in given array.
    maxvalue = -2147483647
    minvalue = 2147483647
    for i in range(n):
      
        maxvalue = max(maxvalue, arr[i])
        minvalue = min(minvalue, arr[i])
      
  
    mark = [0 for i in range(maxvalue + 2)]
    value = [0 for i in range(maxvalue + 2)]
  
    # Marking the presence of each array element
    # and initialising the number of possible
    # full binary tree for each integer equal
    # to 1 because single node will also
    # contribute as a full binary tree.
    for i in range(n):
      
        mark[arr[i]] = 1
        value[arr[i]] = 1
      
  
    # From minimum value to maximum value
    # of array finding the number of all 
    # possible Full Binary Trees.
    ans = 0
    for i in range(minvalue, maxvalue + 1):
      
        # Find if value present in the array
        if (mark[i] != 0):
          
            # For each multiple of i, less than
            # equal to maximum value of array
            j = i + i
            while(j <= maxvalue and j // i <= i): 
              
                # If multiple is not present in the
                # array then continue.
                if (mark[j] == 0):
                    continue
  
                # Finding the number of possible Full
                # binary trees for multiple j by
                # multiplying number of possible Full
                # binary tree from the number i and
                # number of possible Full binary tree
                # from i/j.
                value[j] = value[j] + (value[i] * value[j // i])
  
                # Condition for possibility when left
                # child became right child and vice versa.
                if (i != j // i):
                    value[j] = value[j] + (value[i] * value[j // i])
                j += i         
              
  
        ans += value[i]
      
    return ans
  
# Driver Code
arr = [ 2, 3, 4, 6 ]
n = len(arr)
  
print(numoffbt(arr, n))
  
# This code is contributed by Anant Agarwal.


C#




// C# program to find number of 
// full binary tree such that each
// node is product of its children.
using System;
  
class GFG
{
    // Return the number of all possible full binary
    // tree with given product property.
    static int numoffbt(int []arr, int n)
    {
        // Finding the minimum and maximum values in
        // given array.
        int maxvalue = -2147483647, minvalue = 2147483647;
        for (int i = 0; i < n; i++)
        {
            maxvalue = Math.Max(maxvalue, arr[i]);
            minvalue = Math.Min(minvalue, arr[i]);
        }
       
        int []mark=new int[maxvalue + 2];
        int []value=new int[maxvalue + 2];
        for(int i = 0;i < maxvalue + 2; i++)
            {
                mark[i]=0;
                value[i]=0;
            }
       
        // Marking the presence of each array element
        // and initialising the number of possible
        // full binary tree for each integer equal
        // to 1 because single node will also
        // contribute as a full binary tree.
        for (int i = 0; i < n; i++)
        {
            mark[arr[i]] = 1;
            value[arr[i]] = 1;
        }
       
        // From minimum value to maximum value of array
        // finding the number of all possible Full
        // Binary Trees.
        int ans = 0;
        for (int i = minvalue; i <= maxvalue; i++)
        {
            // Find if value present in the array
            if (mark[i] != 0)
            {
                // For each multiple of i, less than
                // equal to maximum value of array
                for (int j = i + i;
                     j <= maxvalue && j/i <= i; j += i)
                {
                    // If multiple is not present in the
                    // array then continue.
                    if (mark[j] == 0)
                        continue;
       
                    // Finding the number of possible Full
                    // binary trees for multiple j by
                    // multiplying number of possible Full
                    // binary tree from the number i and
                    // number of possible Full binary tree
                    // from i/j.
                    value[j] = value[j] + (value[i] * value[j/i]);
       
                    // Condition for possibility when left
                    // child became right child and vice versa.
                    if (i != j/i)
                        value[j] = value[j] + (value[i] * value[j/i]);
                }
            }
       
            ans += value[i];
        }
       
        return ans;
    }
      
    // Driver code
    public static void Main()
    {
        int []arr = { 2, 3, 4, 6 };
        int n = arr.Length;
       
        Console.Write(numoffbt(arr, n));
    }
}
  
// This code is contributed by Anant Agarwal.


Javascript




<script>
// Javascript program to find number of full binary tree
// such that each node is product of its children.
  
  
// Return the number of all possible full binary
// tree with given product property.
function numoffbt(arr, n) {
    // Finding the minimum and maximum values in
    // given array.
    let maxvalue = Number.MIN_SAFE_INTEGER, minvalue = Number.MAX_SAFE_INTEGER;
    for (let i = 0; i < n; i++) {
        maxvalue = Math.max(maxvalue, arr[i]);
        minvalue = Math.min(minvalue, arr[i]);
    }
  
    let mark = new Array(maxvalue + 2).fill(0);
    let value = new Array(maxvalue + 2).fill(0);
  
  
    // Marking the presence of each array element
    // and initialising the number of possible
    // full binary tree for each integer equal
    // to 1 because single node will also
    // contribute as a full binary tree.
    for (let i = 0; i < n; i++) {
        mark[arr[i]] = 1;
        value[arr[i]] = 1;
    }
  
    // From minimum value to maximum value of array
    // finding the number of all possible Full
    // Binary Trees.
    let ans = 0;
    for (let i = minvalue; i <= maxvalue; i++) {
        // Find if value present in the array
        if (mark[i]) {
            // For each multiple of i, less than
            // equal to maximum value of array
            for (let j = i + i;
                j <= maxvalue && j / i <= i; j += i) {
                // If multiple is not present in the
                // array then continue.
                if (!mark[j])
                    continue;
  
                // Finding the number of possible Full
                // binary trees for multiple j by
                // multiplying number of possible Full
                // binary tree from the number i and
                // number of possible Full binary tree
                // from i/j.
                value[j] = value[j] + (value[i] * value[j / i]);
  
                // Condition for possibility when left
                // child became right child and vice versa.
                if (i != j / i)
                    value[j] = value[j] + (value[i] * value[j / i]);
            }
        }
  
        ans += value[i];
    }
  
    return ans;
}
  
// Driven Program
let arr = [2, 3, 4, 6];
let n = arr.length;
document.write(numoffbt(arr, n) + "<br>");
  
// This code is contributed by _saurabh_jaiswal.
</script>


Output

7

Time Complexity: O(N^2) ,where N is the number of nodes in given binary tree.

Auxiliary Space: O(N)

 



Similar Reads

Minimize sum of node values by filling given empty Tree such that each node is GCD of its children
Given a Binary Tree consisting of N nodes having no values in it and an integer X, that represents the value of the root node, the task is to find the minimum sum of all the nodes value of the given Tree such that the value of each node must be the value of GCDs of its children. Also, no two siblings can have the same value. Examples: Input: Output
11 min read
Second unique smallest value of given Binary Tree whose each node is minimum of its children
Given a full binary tree where each node value is the same as the minimum value between its children, the task is to find the second minimum unique value of the tree. Examples: Input: tree: [caption width="800"]Example of the problem statement[/caption] Output: 5Explanation: All the unique values present in the tree are 2, 5 and 7.The second smalle
19 min read
Minimize cost to split an array into K subsets such that the cost of each element is its product with its position in the subset
Given an array arr[] of size N and a positive integer K, the task is to find the minimum possible cost to split the array into K subsets, where the cost of ith element ( 1-based indexing ) of each subset is equal to the product of that element and i. Examples: Input: arr[] = { 2, 3, 4, 1 }, K = 3 Output: 11 Explanation: Split the array arr[] into K
7 min read
Total number of possible Binary Search Trees and Binary Trees with n keys
Total number of possible Binary Search Trees with n different keys (countBST(n)) = Catalan number Cn = (2n)! / ((n + 1)! * n!) For n = 0, 1, 2, 3, … values of Catalan numbers are 1, 1, 2, 5, 14, 42, 132, 429, 1430, 4862, .... So are numbers of Binary Search Trees. Total number of possible Binary Trees with n different keys (countBT(n)) = countBST(n
12 min read
Minimize changes to convert into Tree with root 1, even left children and odd right children
Given, a binary tree, the task is to convert this tree using minimum number of increment-decrement operations into a tree which satisfies the following conditions: The root node is always 1.Every left child of a node is even.Every right child of a node is odd. Return and print the minimum number of increment-decrement operations required at the end
10 min read
General Tree (Each node can have arbitrary number of children) Level Order Traversal
Given a generic tree, perform a Level order traversal and print all of its nodes Examples: Input : 10 / / \ \ 2 34 56 100 / \ | / | \ 77 88 1 7 8 9 Output : 10 2 34 56 100 77 88 1 7 8 9 Input : 1 / / \ \ 2 3 4 5 / \ | / | \ 6 7 8 9 10 11 Output : 1 2 3 4 5 6 7 8 9 10 11 The approach to this problem is similar to Level Order traversal in a binary tr
7 min read
Minimum count of Full Binary Trees such that the count of leaves is N
Given an integer N and an infinite number of Full Binary Trees of different depths, the task is to choose minimum number of trees such that the sum of the count of leaf nodes in each of the tree is N.Example: Input: N = 7 Output: 3 Trees with depths 2, 1 and 0 can be picked with the number of leaf nodes as 4, 2 and 1 respectively. (4 + 2 + 1) = 7In
3 min read
Count of nodes in a Binary tree with immediate children as its factors
Given a Binary Tree, the task is to print the count of nodes whose immediate children are its factors. Examples: Input: 1 / \ 15 20 / \ / \ 3 5 4 2 \ / 2 3 Output: 2 Explanation: Children of 15 (3, 5) are factors of 15 Children of 20 (4, 2) are factors of 20 Input: 7 / \ 210 14 / \ \ 70 14 30 / \ / \ 2 5 10 15 / 23 Output:3 Explanation: Children of
15 min read
Construct Full Binary Tree using its Preorder traversal and Preorder traversal of its mirror tree
Given two arrays that represent Preorder traversals of a full binary tree and its mirror tree, we need to write a program to construct the binary tree using these two Preorder traversals.A Full Binary Tree is a binary tree where every node has either 0 or 2 children. Note: It is not possible to construct a general binary tree using these two traver
12 min read
Generate longest possible array with product K such that each array element is divisible by its previous adjacent element
Given an integer K, the task is to construct an array of maximum length with product of all array elements equal to K, such that each array element except the first one is divisible by its previous adjacent element.Note: Every array element in the generated array must be greater than 1. Examples: Input: K = 4Output: {2, 2}Explanation:The second ele
7 min read
Article Tags :
Practice Tags :