Calculate number of nodes in all subtrees | Using DFS

• Difficulty Level : Medium
• Last Updated : 30 Jun, 2021

Given a tree in the 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 the 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

Explanation: 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 the concept of DFS and DP, where we should process each edge only once and count[] value of 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;
{
// 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];
}
}

Javascript



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: 