Level of Each node in a Tree from source node ( using BFS ) | Python3 Program to determine level of each node and print level ; function to determine level of each node starting from x using BFS ; array to store level of each node ; create a queue ; enqueue element x ; initialize level of source node to 0 ; marked it as visited ; do until queue is empty ; get the first element of queue ; traverse neighbors of node x ; b is neighbor of node x ; if b is not marked already ; enqueue b in queue ; level of b is level of x + 1 ; mark b ; display all nodes and their levels ; Driver Code ; adjacency graph for tree ; call levels function with source as 0
import queue NEW_LINE def printLevels ( graph , V , x ) : NEW_LINE INDENT level = [ None ] * V NEW_LINE marked = [ False ] * V NEW_LINE que = queue . Queue ( ) NEW_LINE que . put ( x ) NEW_LINE level [ x ] = 0 NEW_LINE marked [ x ] = True NEW_LINE while ( not que . empty ( ) ) : NEW_LINE INDENT x = que . get ( ) NEW_LINE for i in range ( len ( graph [ x ] ) ) : NEW_LINE INDENT b = graph [ x ] [ i ] NEW_LINE if ( not marked [ b ] ) : NEW_LINE INDENT que . put ( b ) NEW_LINE level [ b ] = level [ x ] + 1 NEW_LINE marked [ b ] = True NEW_LINE DEDENT DEDENT DEDENT print ( " Nodes " , " ▁ " , " Level " ) NEW_LINE for i in range ( V ) : NEW_LINE INDENT print ( " ▁ " , i , " ▁ - - > ▁ " , level [ i ] ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT V = 8 NEW_LINE graph = [ [ ] for i in range ( V ) ] NEW_LINE graph [ 0 ] . append ( 1 ) NEW_LINE graph [ 0 ] . append ( 2 ) NEW_LINE graph [ 1 ] . append ( 3 ) NEW_LINE graph [ 1 ] . append ( 4 ) NEW_LINE graph [ 1 ] . append ( 5 ) NEW_LINE graph [ 2 ] . append ( 5 ) NEW_LINE graph [ 2 ] . append ( 6 ) NEW_LINE graph [ 6 ] . append ( 7 ) NEW_LINE printLevels ( graph , V , 0 ) NEW_LINE DEDENT