# Count the number of nodes at given level in a tree using BFS.

Given a tree represented as undirected graph. Count the number of nodes at given level l. It may be assumed that vertex 0 is root of the tree.

Examples:

```Input :   7
0 1
0 2
1 3
1 4
1 5
2 6
2
Output :  4

Input : 6
0 1
0 2
1 3
2 4
2 5
2
Output : 3
```

BFS is a traversing algorithm which start traversing from a selected node (source or starting node) and traverse the graph layer wise thus exploring the neighbour nodes (nodes which are directly connected to source node). Then, move towards the next-level neighbour nodes.
As the name BFS suggests, traverse the graph breadth wise as follows:

1. First move horizontally and visit all the nodes of the current layer.
2. Move to the next layer.

In this code, while visiting each node, the level of that node is set with an increment in the level of its parent node i.e., level[child] = level[parent] + 1. This is how the level of each node is determined. The root node lies at level zero in the tree.

Explanation :

```     0         Level 0
/   \
1     2      Level 1
/ |\    |
3 4 5   6      Level 2```

Given a tree with 7 nodes and 6 edges in which node 0 lies at 0 level. Level of 1 can be updated as : level = level +1 as 0 is the parent node of 1. Similarly, the level of other nodes can be updated by adding 1 to the level of their parent.
level = level + 1, i.e level = 0 + 1 = 1.
level = level + 1, i.e level = 1 + 1 = 2.
level = level + 1, i.e level = 1 + 1 = 2.
level = level + 1, i.e level = 1 + 1 = 2.
level = level + 1, i.e level = 1 + 1 = 2.

Then, count of number of nodes which are at level l(i.e, l=2) is 4 (node:- 3, 4, 5, 6)

## C++

 `// C++ Program to print ` `// count of nodes ` `// at given level. ` `#include ` `#include ` ` `  `using` `namespace` `std; ` ` `  `// This class represents ` `// a directed graph ` `// using adjacency ` `// list representation ` `class` `Graph { ` `    ``// No. of vertices ` `    ``int` `V; ` ` `  `    ``// Pointer to an ` `    ``// array containing ` `    ``// adjacency lists ` `    ``list<``int``>* adj; ` ` `  `public``: ` `    ``// Constructor ` `    ``Graph(``int` `V); ` ` `  `    ``// function to add ` `    ``// an edge to graph ` `    ``void` `addEdge(``int` `v, ``int` `w); ` ` `  `    ``// Returns count of nodes at ` `    ``// level l from given source. ` `    ``int` `BFS(``int` `s, ``int` `l); ` `}; ` ` `  `Graph::Graph(``int` `V) ` `{ ` `    ``this``->V = V; ` `    ``adj = ``new` `list<``int``>[V]; ` `} ` ` `  `void` `Graph::addEdge(``int` `v, ``int` `w) ` `{ ` `    ``// Add w to v’s list. ` `    ``adj[v].push_back(w); ` ` `  `    ``// Add v to w's list. ` `    ``adj[w].push_back(v); ` `} ` ` `  `int` `Graph::BFS(``int` `s, ``int` `l) ` `{ ` `    ``// Mark all the vertices ` `    ``// as not visited ` `    ``bool``* visited = ``new` `bool``[V]; ` `    ``int` `level[V]; ` ` `  `    ``for` `(``int` `i = 0; i < V; i++) { ` `        ``visited[i] = ``false``; ` `        ``level[i] = 0; ` `    ``} ` ` `  `    ``// Create a queue for BFS ` `    ``list<``int``> queue; ` ` `  `    ``// Mark the current node as ` `    ``// visited and enqueue it ` `    ``visited[s] = ``true``; ` `    ``queue.push_back(s); ` `    ``level[s] = 0; ` ` `  `    ``while` `(!queue.empty()) { ` ` `  `        ``// Dequeue a vertex from ` `        ``// queue and print it ` `        ``s = queue.front(); ` `        ``queue.pop_front(); ` ` `  `        ``// Get all adjacent vertices ` `        ``// of the dequeued vertex s. ` `        ``// If a adjacent has not been ` `        ``// visited, then mark it ` `        ``// visited and enqueue it ` `        ``for` `(``auto` `i = adj[s].begin(); ` `                  ``i != adj[s].end(); ++i) { ` `            ``if` `(!visited[*i]) { ` ` `  `                ``// Setting the level ` `                ``// of each node with ` `                ``// an increment in the ` `                ``// level of parent node ` `                ``level[*i] = level[s] + 1; ` `                ``visited[*i] = ``true``; ` `                ``queue.push_back(*i); ` `            ``} ` `        ``} ` `    ``} ` ` `  `    ``int` `count = 0; ` `    ``for` `(``int` `i = 0; i < V; i++)  ` `        ``if` `(level[i] == l) ` `            ``count++;     ` `    ``return` `count;   ` `} ` ` `  `// Driver program to test ` `// methods of graph class ` `int` `main() ` `{ ` `    ``// Create a graph given ` `    ``// in the above diagram ` `    ``Graph g(6); ` `    ``g.addEdge(0, 1); ` `    ``g.addEdge(0, 2); ` `    ``g.addEdge(1, 3); ` `    ``g.addEdge(2, 4); ` `    ``g.addEdge(2, 5); ` ` `  `    ``int` `level = 2; ` ` `  `    ``cout << g.BFS(0, level); ` ` `  `    ``return` `0; ` `} `

## C#

 `// C# program to print count of nodes  ` `// at given level.  ` `using` `System; ` `using` `System.Collections.Generic; ` `using` `System.Linq; ` `using` `System.Text; ` ` `  `// This class represents  ` `// a directed graph  ` `// using adjacency  ` `// list representation  ` `class` `Graph{ ` ` `  `// No. of vertices      ` `private` `int` `_V;  ` ` `  `LinkedList<``int``>[] _adj;  ` ` `  `public` `Graph(``int` `V) ` `{ ` `    ``_adj = ``new` `LinkedList<``int``>[V]; ` ` `  `    ``for``(``int` `i = 0; i < _adj.Length; i++) ` `    ``{ ` `        ``_adj[i] = ``new` `LinkedList<``int``>(); ` `    ``} ` `    ``_V = V; ` `} ` ` `  `public` `void` `AddEdge(``int` `v, ``int` `w) ` `{ ` `     `  `    ``// Add w to v’s list.  ` `    ``_adj[v].AddLast(w); ` `} ` ` `  `public` `int` `BreadthFirstSearch(``int` `s,``int` `l) ` `{ ` `     `  `    ``// Mark all the vertices  ` `    ``// as not visited  ` `    ``bool``[] visited = ``new` `bool``[_V]; ` `    ``int``[] level = ``new` `int``[_V]; ` `     `  `    ``for``(``int` `i = 0; i < _V; i++) ` `    ``{ ` `        ``visited[i] = ``false``; ` `        ``level[i] = 0; ` `    ``} ` `     `  `    ``// Create a queue for BFS  ` `    ``LinkedList<``int``> queue = ``new` `LinkedList<``int``>(); ` `     `  `    ``// Mark the current node as  ` `    ``// visited and enqueue it  ` `    ``visited[s] = ``true``; ` `    ``level[s] = 0; ` `    ``queue.AddLast(s);          ` ` `  `    ``while``(queue.Any()) ` `    ``{ ` `         `  `        ``// Dequeue a vertex from  ` `        ``// queue and print it ` `        ``s = queue.First(); ` `         `  `        ``// Console.Write( s + " " ); ` `        ``queue.RemoveFirst(); ` ` `  `        ``LinkedList<``int``> list = _adj[s]; ` ` `  `        ``foreach``(``var` `val ``in` `list)              ` `        ``{ ` `            ``if` `(!visited[val]) ` `            ``{ ` `                ``visited[val] = ``true``; ` `                ``level[val] = level[s] + 1; ` `                ``queue.AddLast(val); ` `            ``} ` `        ``} ` `    ``} ` `     `  `    ``int` `count = 0; ` `    ``for``(``int` `i = 0; i < _V; i++) ` `        ``if` `(level[i] == l) ` `            ``count++; ` `             `  `    ``return` `count; ` `} ` `} ` ` `  `// Driver code ` `class` `GFG{ ` `     `  `static` `void` `Main(``string``[] args) ` `{ ` `     `  `    ``// Create a graph given  ` `    ``// in the above diagram  ` `    ``Graph g = ``new` `Graph(6); ` ` `  `    ``g.AddEdge(0, 1); ` `    ``g.AddEdge(0, 2); ` `    ``g.AddEdge(1, 3); ` `    ``g.AddEdge(2, 4); ` `    ``g.AddEdge(2, 5); ` ` `  `    ``int` `level = 2; ` `     `  `    ``Console.WriteLine(g.BreadthFirstSearch(0, level)); ` `} ` `} ` ` `  `// This code is contributed by anvudemy1 `

Output:

``` 3
```

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up Check out this Author's contributed articles.

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 Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

Improved By : anvudemy1

Article Tags :
Practice Tags :

10

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