# Level of Each node in a Tree from source node (using BFS)

BFS(Breadth First Search) is a graph traversal technique where a node and its neighbors are visited first and then the neighbors of neighbors. In simple terms it traverses level wise from the source. First it traverses level 1 nodes (direct neighbors of source node) and then level 2 nodes (neighbors of neighbors of source node) and so on.

Now, suppose if we have to know at which level all the nodes are at (from source node). Then BFS can be used to determine the level of each node.

**Examples:**

Input : Output : Node Level 0 0 1 1 2 1 3 2 4 2 5 2 6 2 7 3 Explanation :

## C++

`// CPP Program to determine level of each node ` `// and print level ` `#include <iostream> ` `#include <queue> ` `#include <vector> ` `using` `namespace` `std; ` ` ` `// function to determine level of each node starting ` `// from x using BFS ` `void` `printLevels(vector<` `int` `> graph[], ` `int` `V, ` `int` `x) ` `{ ` ` ` `// array to store level of each node ` ` ` `int` `level[V]; ` ` ` `bool` `marked[V]; ` ` ` ` ` `// create a queue ` ` ` `queue<` `int` `> que; ` ` ` ` ` `// enqueue element x ` ` ` `que.push(x); ` ` ` ` ` `// initialize level of source node to 0 ` ` ` `level[x] = 0; ` ` ` ` ` `// marked it as visited ` ` ` `marked[x] = ` `true` `; ` ` ` ` ` `// do until queue is empty ` ` ` `while` `(!que.empty()) { ` ` ` ` ` `// get the first element of queue ` ` ` `x = que.front(); ` ` ` ` ` `// dequeue element ` ` ` `que.pop(); ` ` ` ` ` `// traverse neighbors of node x ` ` ` `for` `(` `int` `i = 0; i < graph[x].size(); i++) { ` ` ` `// b is neighbor of node x ` ` ` `int` `b = graph[x][i]; ` ` ` ` ` `// if b is not marked already ` ` ` `if` `(!marked[b]) { ` ` ` ` ` `// enqueue b in queue ` ` ` `que.push(b); ` ` ` ` ` `// level of b is level of x + 1 ` ` ` `level[b] = level[x] + 1; ` ` ` ` ` `// mark b ` ` ` `marked[b] = ` `true` `; ` ` ` `} ` ` ` `} ` ` ` `} ` ` ` ` ` `// display all nodes and their levels ` ` ` `cout << ` `"Nodes"` ` ` `<< ` `" "` ` ` `<< ` `"Level"` `<< endl; ` ` ` `for` `(` `int` `i = 0; i < V; i++) ` ` ` `cout << ` `" "` `<< i << ` `" --> "` `<< level[i] << endl; ` `} ` ` ` `// Dirver Code ` `int` `main() ` `{ ` ` ` `// adjacency graph for tree ` ` ` `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); ` ` ` ` ` `// call levels function with source as 0 ` ` ` `printLevels(graph, V, 0); ` ` ` ` ` `return` `0; ` `} ` |

*chevron_right*

*filter_none*

## Python3

# Python3 Program to determine level

# of each node and print level

import queue

# function to determine level of

# each node starting from x using BFS

def printLevels(graph, V, x):

# array to store level of each node

level = [None] * V

marked = [False] * V

# create a queue

que = queue.Queue()

# enqueue element x

que.put(x)

# initialize level of source

# node to 0

level[x] = 0

# marked it as visited

marked[x] = True

# do until queue is empty

while (not que.empty()):

# get the first element of queue

x = que.get()

# traverse neighbors of node x

for i in range(len(graph[x])):

# b is neighbor of node x

b = graph[x][i]

# if b is not marked already

if (not marked[b]):

# enqueue b in queue

que.put(b)

# level of b is level of x + 1

level[b] = level[x] + 1

# mark b

marked[b] = True

# display all nodes and their levels

print(“Nodes”, ” “, “Level”)

for i in range(V):

print(” “,i, ” –> “, level[i])

# Driver Code

if __name__ == ‘__main__’:

# adjacency graph for tree

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)

# call levels function with source as 0

printLevels(graph, V, 0)

# This code is contributed by PranchalK

**Output:**

Nodes Level 0 --> 0 1 --> 1 2 --> 1 3 --> 2 4 --> 2 5 --> 2 6 --> 2 7 --> 3

## Recommended Posts:

- Minimum cost path from source node to destination node via an intermediate node
- Minimum edges to be added in a directed graph so that any node can be reachable from a given node
- Right sibling of each node in a tree given as array of edges
- Find all reachable nodes from every node present in a given set
- Number of loops of size k starting from a specific node
- k'th heaviest adjacent node in a graph where each vertex has weight
- Number of ways to select a node from each connected component
- Count single node isolated sub-graphs in a disconnected graph
- Count the number of nodes at a given level in a tree using DFS
- Count the number of nodes at given level in a tree using BFS.
- Number of Walks from source to destination
- Print all paths from a given source to a destination using BFS
- Print all paths from a given source to a destination
- Find if there is a path of more than k length from a source
- Minimum distance to the corner of a grid from source

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.