Calculate number of nodes in all subtrees | Using DFS

Given a tree in form of adjacency list we have to calculate the number of nodes in the subtree of each node, while calculating the number of nodes in the subtree of a particular node that node will also be added as a node in subtree hence number of nodes in subtree of leaves is 1.

Examples:

Input : Consider the Graph mentioned below: Output : Nodes in subtree of 1 : 5
Nodes in subtree of 2 : 1
Nodes in subtree of 3 : 1
Nodes in subtree of 4 : 3
Nodes in subtree of 5 : 1

Input : Consider the Graph mentioned below: Output : Nodes in subtree of 1 : 7
Nodes in subtree of 2 : 2
Nodes in subtree of 3 : 1
Nodes in subtree of 4 : 3
Nodes in subtree of 5 : 1
Nodes in subtree of 6 : 1
Nodes in subtree of 7 : 1

Expalnation: First we should calculate value count[s] : the number of nodes in subtree of node s. Where subtree contains the node itself and all the nodes in the subtree of its children. Thus, we can calculate the number of nodes recursively using concept of DFS and DP, where we should process each edge only once and count[] value of a children used in calculating count[] of its parent expressing the concept of DP(Dynamic programming).
Time Complexity : O(n) [in processing of all (n-1) edges].

Algorithm :
void numberOfNodes(int s, int e)
{
vector::iterator u;
count1[s] = 1;
for (u = adj[s].begin(); u != adj[s].end(); u++)
{
// condition to omit reverse path
// path from children to parent
if (*u == e)
continue;

// recursive call for DFS
numberOfNodes(*u, s);

// update count[] value of parent using
// its children
count1[s] += count1[*u];
}
}

C#

Output:

Nodes in subtree of 1: 7
Nodes in subtree of 2: 2
Nodes in subtree of 3: 1
Nodes in subtree of 4: 3
Nodes in subtree of 5: 1
Nodes in subtree of 6: 1
Nodes in subtree of 7: 1

Input and Output illustration: This article is contributed by Shivam Pradhan (anuj_charm). If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

My Personal Notes arrow_drop_up

Article Tags :
Practice Tags :

1

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.