VOOZH about

URL: https://www.geeksforgeeks.org/dsa/count-of-subtrees-possible-from-an-n-ary-tree/

⇱ Count of subtrees possible from an N-ary Tree - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Count of subtrees possible from an N-ary Tree

Last Updated : 23 Jul, 2025

Given an N-ary tree consisting of N nodes having values 0 to (N - 1), the task is to find the total number of subtrees present in the given tree. Since the count can be very large, so print the count modulo 1000000007.

Examples:

Input: N = 3
           0
        / 
     1
   /
2
Output: 7
Explanation:
The total number of subtrees nodes are {}, {0}, {1}, {2}, {0, 1}, {1, 2}, {0, 1, 2}. 

Input: N = 2
        0
     /
  1
Output: 4

Approach: The approach for solving the given problem is to perform DFS Traversal on the given tree. Follow the steps below to solve the problem:

  • Initialize a variable, say count as 0, to store the count of the total number of subtrees present in the given tree.
  • Declare a function DFS(int src, int parent) to count the number of subtrees for the node src and perform the following operations: 
    • Initialize a variable, say res as 1.
    • Traverse the adjacency list of the current node and if the node in the adjacency list, say X is not the same as the parent node, then recursively call the DFS function for the node X and node src as the parent node as DFS(X, src).
    • Let the value returned to the above recursive call is value, then update the value of res as (res * (value + 1)) % (109 + 7).
    • Update the value of count as (count + res) % (109 + 7).
    • Return the value of res from each recursive call.
  • Call the function DFS() for the root node 1.
  • After completing the above steps, print the value of count as the result.

Below is the implementation of the above approach:


Output: 
7

 

Time Complexity: O(N)
Auxiliary Space: O(N)

Comment