VOOZH about

URL: https://www.geeksforgeeks.org/dsa/count-number-trees-forest/

⇱ Count number of trees in a forest - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Count number of trees in a forest

Last Updated : 14 Apr, 2023

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 : 

  1.  Apply DFS on every node. 
  2. Increment count by one if every connected node is visited from one source. 
  3. Again perform DFS traversal if some nodes yet not visited. 
  4.  Count will give the number of trees in forest. 

Implementation:


Output
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++

  •    Define a bfs function that takes the forest, a start node, and a visited array as inputs. The function performs BFS starting from the start node and marks all visited nodes in the visited array.
  •    Inside the bfs function, create a queue q to store the nodes that are to be visited in the BFS. Initially, push the start node onto the queue and mark it as visited in the visited array.

Output
The forest has 2 trees.

Time complexity : - O(NM)
Auxiliary Space :- O(MN)

Comment
Article Tags:
Article Tags: