Given an undirected graph containing the nodes of a tree as vertices. The goal is to find the count of nodes at a given level of the tree using BFS( breadth first search ) algorithm.
BFS Algorithm:-
This algorithm starts traversing the graph/tree level by level. Starting from node at level 0, it will first traverse all nodes directly connected to it at level 1, then will traverse all nodes at next level and so on.
For Example
Input - level=2
Output - Count of number of nodes at given level in a tree using BFS are: 1
Explanation - As shown above all levels have a single node in the graph.
Input - level=1
Output - Count of number of nodes at given level in a tree using BFS are: 2
Explanation - As shown above all levels have a single node in the graph. The nodes are 1, 2.
In this approach we will traverse each node and set their levels as one level more than its parent. We will represent a graph using adjacency list representation.
If starting node is 0 then
level[0]=0,
level[1] = level[0]+1 = 1, level[2]=level[0]+1=1
level[3]= level[2]+1 = 2, level[4]=level[2]+1=2
#include <bits/stdc++.h> using namespace std; class node { int data; list < int > * next; public: node(int data) { this -> data = data; next = new list < int > [data]; } void insert(int val, int point) { next[val].push_back(point); next[point].push_back(val); } int count_nodes(int a, int b); }; int node::count_nodes(int a, int b) { int count = 0; bool * check = new bool[data]; int arr[data]; for (int i = 0; i < data; i++) { check[i] = false; arr[i] = 0; } list < int > l1; check[a] = true; l1.push_back(a); arr[a] = 0; while (!l1.empty()) { a = l1.front(); l1.pop_front(); for (auto it = next[a].begin(); it != next[a].end(); ++it) { if (!check[ * it]) { arr[ * it] = arr[a] + 1; check[ * it] = true; l1.push_back( * it); } } } for (int i = 0; i < data; i++) { if (arr[i] == b) { count++; } } return count; } int main() { node n1(5); n1.insert(1, 2); n1.insert(0, 3); n1.insert(1, 3); n1.insert(2, 4); int level = 1; cout << "Count of number of nodes at given level in a tree using BFS are: " << n1.count_nodes(0, level); return 0; }
If we run the above code it will generate the following output −
Count of number of nodes at given level in a tree using BFS are: 1