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 where a node and its neighbours are visited first and then the neighbours of neighbours. In simple terms, it traverses level-wise from the source. First, it traverses level 1 nodes (direct neighbours of source node) and then level 2 nodes (neighbours of source node) and so on. The BFS can be used to determine the level of each node from a given source node.
Algorithm:
- Create the tree, a queue to store the nodes and insert the root or starting node in the queue. Create an extra array level of size v (number of vertices) and create a visited array.
- Run a loop while size of queue is greater than 0.
- Mark the current node as visited.
- Pop one node from the queue and insert its childrens (if present) and update the size of the inserted node as level[child] = level[node] + 1.
- Print all the node and its level.
Implementation:
C++
#include <bits/stdc++.h>
using namespace std;
void printLevels(vector<int> graph[], int V, int x)
{
int level[V];
bool marked[V];
queue<int> que;
que.push(x);
level[x] = 0;
marked[x] = true;
while (!que.empty()) {
x = que.front();
que.pop();
for (int i = 0; i < graph[x].size(); i++) {
int b = graph[x][i];
if (!marked[b]) {
que.push(b);
level[b] = level[x] + 1;
marked[b] = true;
}
}
}
cout << "Nodes"
<< " "
<< "Level" << endl;
for (int i = 0; i < V; i++)
cout << " " << i << " --> " << level[i] << endl;
}
int main()
{
int V = 8;
vector<int> graph[V];
graph[0].push_back(1);
graph[0].push_back(2);
graph[1].push_back(3);
graph[1].push_back(4);
graph[1].push_back(5);
graph[2].push_back(5);
graph[2].push_back(6);
graph[6].push_back(7);
printLevels(graph, V, 0);
return 0;
}
|
Java
import java.util.*;
class GFG {
static void printLevels(Vector<Vector<Integer> > graph,
int V, int x)
{
int level[] = new int[V];
boolean marked[] = new boolean[V];
Queue<Integer> que = new LinkedList<Integer>();
que.add(x);
level[x] = 0;
marked[x] = true;
while (que.size() > 0) {
x = que.peek();
que.remove();
for (int i = 0; i < graph.get(x).size(); i++) {
int b = graph.get(x).get(i);
if (!marked[b]) {
que.add(b);
level[b] = level[x] + 1;
marked[b] = true;
}
}
}
System.out.println("Nodes"
+ " "
+ "Level");
for (int i = 0; i < V; i++)
System.out.println(" " + i + " --> "
+ level[i]);
}
public static void main(String args[])
{
int V = 8;
Vector<Vector<Integer> > graph
= new Vector<Vector<Integer> >();
for (int i = 0; i < V + 1; i++)
graph.add(new Vector<Integer>());
graph.get(0).add(1);
graph.get(0).add(2);
graph.get(1).add(3);
graph.get(1).add(4);
graph.get(1).add(5);
graph.get(2).add(5);
graph.get(2).add(6);
graph.get(6).add(7);
printLevels(graph, V, 0);
}
}
|
Python3
import queue
def printLevels(graph, V, x):
level = [None] * V
marked = [False] * V
que = queue.Queue()
que.put(x)
level[x] = 0
marked[x] = True
while (not que.empty()):
x = que.get()
for i in range(len(graph[x])):
b = graph[x][i]
if (not marked[b]):
que.put(b)
level[b] = level[x] + 1
marked[b] = True
print("Nodes", " ", "Level")
for i in range(V):
print(" ", i, " --> ", level[i])
if __name__ == '__main__':
V = 8
graph = [[] for i in range(V)]
graph[0].append(1)
graph[0].append(2)
graph[1].append(3)
graph[1].append(4)
graph[1].append(5)
graph[2].append(5)
graph[2].append(6)
graph[6].append(7)
printLevels(graph, V, 0)
|
C#
using System;
using System.Collections.Generic;
class GFG {
static void printLevels(List<List<int> > graph, int V,
int x)
{
int[] level = new int[V];
Boolean[] marked = new Boolean[V];
Queue<int> que = new Queue<int>();
que.Enqueue(x);
level[x] = 0;
marked[x] = true;
while (que.Count > 0) {
x = que.Peek();
que.Dequeue();
for (int i = 0; i < graph[x].Count; i++) {
int b = graph[x][i];
if (!marked[b]) {
que.Enqueue(b);
level[b] = level[x] + 1;
marked[b] = true;
}
}
}
Console.WriteLine("Nodes"
+ " "
+ "Level");
for (int i = 0; i < V; i++)
Console.WriteLine(" " + i + " --> " + level[i]);
}
public static void Main(String[] args)
{
int V = 8;
List<List<int> > graph = new List<List<int> >();
for (int i = 0; i < V + 1; i++)
graph.Add(new List<int>());
graph[0].Add(1);
graph[0].Add(2);
graph[1].Add(3);
graph[1].Add(4);
graph[1].Add(5);
graph[2].Add(5);
graph[2].Add(6);
graph[6].Add(7);
printLevels(graph, V, 0);
}
}
|
Javascript
<script>
function printLevels(graph, V, x)
{
var level = Array(V);
var marked = Array(V).fill(false);
var que = [];
que.push(x);
level[x] = 0;
marked[x] = true;
while (que.length > 0)
{
x = que[0];
que.shift();
for (var i = 0; i < graph[x].length; i++)
{
var b = graph[x][i];
if (!marked[b])
{
que.push(b);
level[b] = level[x] + 1;
marked[b] = true;
}
}
}
document.write("Nodes" + " " + "Level<br>");
for (var i = 0; i < V; i++)
document.write(" " + i +" --> " + level[i]+"<br>");
}
var V = 8;
var graph = Array.from(Array(V+1), ()=>Array());
graph[0].push(1);
graph[0].push(2);
graph[1].push(3);
graph[1].push(4);
graph[1].push(5);
graph[2].push(5);
graph[2].push(6);
graph[6].push(7);
printLevels(graph, V, 0);
</script>
|
OutputNodes Level
0 --> 0
1 --> 1
2 --> 1
3 --> 2
4 --> 2
5 --> 2
6 --> 2
7 --> 3
Complexity Analysis:
- Time Complexity: O(n).
In BFS traversal every node is visited only once, so Time Complexity is O(n). - Space Complexity: O(n).
The space is required to store the nodes in a queue.
Last Updated :
01 Aug, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...