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