Count of subtrees possible from an N | Python3 program of the above approach ; Adjacency list to represent the graph ; Stores the count of subtrees possible from given N - ary Tree ; Utility function to count the number of subtrees possible from given N - ary Tree ; Stores the count of subtrees when cur node is the root ; Traverse the adjacency list ; Iterate over every ancestor ; Calculate product of the number of subtrees for each child node ; Update the value of ans ; Return the resultant count ; Function to count the number of subtrees in the given tree ; Initialize an adjacency matrix ; Add the edges ; Function Call to count the number of subtrees possible ; Prcount of subtrees ; Driver Code
MAX = 300004 NEW_LINE graph = [ [ ] for i in range ( MAX ) ] NEW_LINE mod = 10 ** 9 + 7 NEW_LINE ans = 0 NEW_LINE def countSubtreesUtil ( cur , par ) : NEW_LINE INDENT global mod , ans NEW_LINE res = 1 NEW_LINE for i in range ( len ( graph [ cur ] ) ) : NEW_LINE INDENT v = graph [ cur ] [ i ] NEW_LINE if ( v == par ) : NEW_LINE INDENT continue NEW_LINE DEDENT res = ( res * ( countSubtreesUtil ( v , cur ) + 1 ) ) % mod NEW_LINE DEDENT ans = ( ans + res ) % mod NEW_LINE return res NEW_LINE DEDENT def countSubtrees ( N , adj ) : NEW_LINE INDENT for i in range ( N - 1 ) : NEW_LINE INDENT a = adj [ i ] [ 0 ] NEW_LINE b = adj [ i ] [ 1 ] NEW_LINE graph [ a ] . append ( b ) NEW_LINE graph [ b ] . append ( a ) NEW_LINE DEDENT countSubtreesUtil ( 1 , 1 ) NEW_LINE print ( ans + 1 ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 3 NEW_LINE adj = [ [ 0 , 1 ] , [ 1 , 2 ] ] NEW_LINE countSubtrees ( N , adj ) NEW_LINE DEDENT