![]() |
VOOZH | about |
Given n nodes of a forest (collection of trees), find the number of trees in the forest.
Examples :
Input : edges[] = {0, 1}, {0, 2}, {3, 4}
Output : 2
Explanation : There are 2 trees
0 3
/ \ \
1 2 4
Approach :
Implementation:
2
Time Complexity: O(V + E), where V is the number of vertices and E is the number of edges.
Space Complexity: O(V). We use an array of size V to store the visited nodes.
Approach:- Here's an implementation of counting the number of trees in a forest using BFS in C++
The forest has 2 trees.
Time complexity : - O(NM)
Auxiliary Space :- O(MN)