Level of Each node in a Tree from source node ( using BFS ) | C # 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 ; dequeue element ; 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
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 ) ; } }