Count the number of nodes at given level in a tree using BFS.
Last Updated :
28 Mar, 2023
Given a tree represented as an undirected graph. Count the number of nodes at a given level l. It may be assumed that vertex 0 is the 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 that starts traversing from a selected node (source or starting node) and traverses the graph layer-wise thus exploring the neighbour nodes (nodes that are directly connected to the source node). Then, move towards the next-level neighbor nodes.
As the name BFS suggests, traverse the graph breadth wise as follows:
- First move horizontally and visit all the nodes of the current layer.
- 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[1] = level[0] +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[2] = level[0] + 1, i.e level[2] = 0 + 1 = 1.
level[3] = level[1] + 1, i.e level[3] = 1 + 1 = 2.
level[4] = level[1] + 1, i.e level[4] = 1 + 1 = 2.
level[5] = level[1] + 1, i.e level[5] = 1 + 1 = 2.
level[6] = level[2] + 1, i.e level[6] = 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)
Implementation:
C++
#include <iostream>
#include <list>
using namespace std;
class Graph {
int V;
list< int >* adj;
public :
Graph( int V);
void addEdge( int v, int w);
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)
{
adj[v].push_back(w);
adj[w].push_back(v);
}
int Graph::BFS( int s, int l)
{
bool * visited = new bool [V];
int level[V];
for ( int i = 0; i < V; i++) {
visited[i] = false ;
level[i] = 0;
}
list< int > queue;
visited[s] = true ;
queue.push_back(s);
level[s] = 0;
while (!queue.empty()) {
s = queue.front();
queue.pop_front();
for ( auto i = adj[s].begin();
i != adj[s].end(); ++i) {
if (!visited[*i]) {
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;
}
int main()
{
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;
}
|
Java
import java.util.*;
class Graph
{
int V;
Vector<Integer>[] adj;
@SuppressWarnings ( "unchecked" )
Graph( int V)
{
adj = new Vector[V];
for ( int i = 0 ; i < adj.length; i++)
{
adj[i] = new Vector<>();
}
this .V = V;
}
void addEdge( int v, int w)
{
adj[v].add(w);
adj[w].add(v);
}
int BFS( int s, int l)
{
boolean [] visited = new boolean [V];
int [] level = new int [V];
for ( int i = 0 ; i < V; i++)
{
visited[i] = false ;
level[i] = 0 ;
}
Queue<Integer> queue = new LinkedList<>();
visited[s] = true ;
queue.add(s);
level[s] = 0 ;
int count = 0 ;
while (!queue.isEmpty())
{
s = queue.peek();
queue.poll();
Vector<Integer> list = adj[s];
for ( int i : list)
{
if (!visited[i])
{
visited[i] = true ;
level[i] = level[s] + 1 ;
queue.add(i);
}
}
count = 0 ;
for ( int i = 0 ; i < V; i++)
if (level[i] == l)
count++;
}
return count;
}
}
class GFG {
public static void main(String[] args)
{
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 ;
System.out.print(g.BFS( 0 , level));
}
}
|
Python3
from collections import deque
adj = [[] for i in range ( 1001 )]
def addEdge(v, w):
adj[v].append(w)
adj[w].append(v)
def BFS(s, l):
V = 100
visited = [ False ] * V
level = [ 0 ] * V
for i in range (V):
visited[i] = False
level[i] = 0
queue = deque()
visited[s] = True
queue.append(s)
level[s] = 0
while ( len (queue) > 0 ):
s = queue.popleft()
for i in adj[s]:
if ( not visited[i]):
level[i] = level[s] + 1
visited[i] = True
queue.append(i)
count = 0
for i in range (V):
if (level[i] = = l):
count + = 1
return count
if __name__ = = '__main__' :
addEdge( 0 , 1 )
addEdge( 0 , 2 )
addEdge( 1 , 3 )
addEdge( 2 , 4 )
addEdge( 2 , 5 )
level = 2
print (BFS( 0 , level))
|
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
class Graph{
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)
{
_adj[v].AddLast(w);
}
public int BreadthFirstSearch( int s, int l)
{
bool [] visited = new bool [_V];
int [] level = new int [_V];
for ( int i = 0; i < _V; i++)
{
visited[i] = false ;
level[i] = 0;
}
LinkedList< int > queue = new LinkedList< int >();
visited[s] = true ;
level[s] = 0;
queue.AddLast(s);
while (queue.Any())
{
s = queue.First();
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;
}
}
class GFG{
static void Main( string [] args)
{
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));
}
}
|
Javascript
<script>
let V;
let adj= new Array(1001);
for (let i=0;i<adj.length;i++)
{
adj[i]=[];
}
function addEdge(v,w)
{
adj[v].push(w);
adj[w].push(v);
}
function BFS(s,l)
{
V=100;
let visited = new Array(V);
let level = new Array(V);
for (let i = 0; i < V; i++)
{
visited[i] = false ;
level[i] = 0;
}
let queue = [];
visited[s] = true ;
queue.push(s);
level[s] = 0;
let count = 0;
while (queue.length!=0)
{
s = queue[0];
queue.shift();
let list = adj[s];
for (let i=0;i<list.length;i++)
{
if (!visited[list[i]])
{
visited[list[i]] = true ;
level[list[i]] = level[s] + 1;
queue.push(list[i]);
}
}
count = 0;
for (let i = 0; i < V; i++)
if (level[i] == l)
count++;
}
return count;
}
addEdge(0, 1)
addEdge(0, 2)
addEdge(1, 3)
addEdge(2, 4)
addEdge(2, 5)
let level = 2;
document.write(BFS(0, level));
</script>
|
Time Complexity: O(V+E)
Auxiliary Space: O(V)
Similar Reads
Count the number of nodes at a given level in a tree using DFS
Given an integer l and a tree represented as an undirected graph rooted at vertex 0. The task is to print the number of nodes present at level l. Examples:Â Input: l = 2Â Â Output: 4Â We have already discussed the BFS approach, in this post we will solve it using DFS. Approach: The idea is to travers
8 min read
Level of Each node in a Tree from source node (using BFS)
Given a tree with v vertices, find the level of each node in a tree from the source node. Examples: Input : Output : Node Level 0 0 1 1 2 1 3 2 4 2 5 2 6 2 7 3 Explanation : Input: Output : Node Level 0 0 1 1 2 1 3 2 4 2 Explanation: Approach: BFS(Breadth-First Search) is a graph traversal technique
8 min read
Count the nodes in the given tree whose weight is a powerful number
Given a tree, and the weights of all the nodes, the task is to count the number of nodes whose weight is a Powerful Number. A number n is said to be Powerful Number if, for every prime factor p of it, p2 also divides it. Example: Input: Output: 3 Explanation: 4, 16 and 25 are powerful weights in the
9 min read
Count the number of common ancestors of given K nodes in a N-ary Tree
Given an N-ary tree root and a list of K nodes, the task is to find the number of common ancestors of the given K nodes in the tree. Example: Input: root = 3 / \ 2 1 / \ / | \ 9 7 8 6 3K = {7, 2, 9}Output: 2 Explanation: The common ancestors of the nodes 7, 9 and 2 are 2 and 3 Input: root = 2 \ 1 \
10 min read
Count the number of Nodes in a Binary Tree in Constant Space
Given a binary tree having N nodes, count the number of nodes using constant O(1) space. This can be done by simple traversals like- Preorder, InOrder, PostOrder, and LevelOrder but these traversals require an extra space which is equal to the height of the tree. Examples: Input: Output: 5Explanatio
10 min read
Count the number of visible nodes in Binary Tree
Given a Binary tree, the task is to find the number of visible nodes in the given binary tree. A node is a visible node if, in the path from the root to the node N, there is no node with greater value than Nâs, Examples: Input: 5 / \ 3 10 / \ / 20 21 1 Output: 4 Explanation: There are 4 visible node
7 min read
Level with maximum number of nodes using DFS in a N-ary tree
Given a N-ary tree, the task is to print the level with the maximum number of nodes. Examples: Input : For example, consider the following tree 1 - Level 1 / \ 2 3 - Level 2 / \ \ 4 5 6 - Level 3 / \ / 7 8 9 - Level 4 Output : Level-3 and Level-4 Approach: Insert all the connecting nodes to a 2-D ve
10 min read
Count the nodes in the given Tree whose weight is a Perfect Number
Given a tree, and the weights of all the nodes, the task is to count the number of nodes whose weight is a Perfect number. A perfect number is a positive integer that is equal to the sum of its proper divisors. Examples: Input: Output: 0 Explanation: There is no node with a weight that is a perfect
8 min read
Count BST nodes that lie in a given range
Given a Binary Search Tree (BST) and a range [l, h], the task is to count the number of nodes in the BST that lie in the given range. Examples: Input: Output: 3Explanation: There are three nodes in range [5, 45] = 5, 10 and 40. Input: Output: 4Explanation: There are four nodes in range [10, 100] = 1
14 min read
Count nodes in the given tree whose weight is a fibonacci number
Given a tree with the weights of all the nodes, the task is to count the number of nodes whose weight is a Fibonacci number.Examples: Input: Output: 2 Explanation: Nodes having weights 5 and 8 are fibonacci nodes. Input: Output: 3 Explanation: Nodes having weights 1, 3 and 8 are fibonacci nodes. App
8 min read