How to determine the level of each node in the given tree?
node level [node] s (source node) 0 1 1 2 1 3 2 4 2 5 2 6 2 7 3
How to determine the level of each node in the given tree?
node level [node] s (source node) 0 1 1 2 1 3 2 4 2 5 2 6 2 7 3
How to determine the level of each node in the given tree?
void bfs (int start) { deque <int > Q; //Double-ended queue Q.push_back( start); distance[ start ] = 0; while( !Q.empty ()) { int v = Q.front( ); Q.pop_front(); for( int i = 0 ; i < edges[v].size(); i++) { /* if distance of neighbour of v from start node is greater than sum of distance of v from start node and edge weight between v and its neighbour (distance between v and its neighbour of v) ,then change it */ if(distance[ edges[ v ][ i ].first ] > distance[ v ] + edges[ v ][ i ].second ) { distance[ edges[ v ][ i ].first ] = distance[ v ] + edges[ v ][ i ].second; /*if edge weight between v and its neighbour is 0 then push it to front of double ended queue else push it to back*/ if(edges[ v ][ i ].second == 0) { Q.push_front( edges[ v ][ i ].first); } else { Q.push_back( edges[ v ][ i ].first); } } } } }
How to determine the level of each node in the given tree?
vector <int> v[10] ; //Vector for maintaining adjacency list explained above int level[10]; //To determine the level of each node bool vis[10]; //Mark the node if visited void bfs(int s) { queue <int> q; q.push(s); level[ s ] = 0 ; //Setting the level of the source node as 0 vis[ s ] = true; while(!q.empty()) { int p = q.front(); q.pop(); for(int i = 0;i < v[ p ].size() ; i++) { if(vis[ v[ p ][ i ] ] == false) { //Setting the level of each node with an increment in the level of parent node level[ v[ p ][ i ] ] = level[ p ]+1; q.push(v[ p ][ i ]); vis[ v[ p ][ i ] ] = true; } } } }
Copyright © 2021 Codeinu
Forgot your account's password or having trouble logging into your Account? Don't worry, we'll help you to get back your account. Enter your email address and we'll send you a recovery link to reset your password. If you are experiencing problems resetting your password contact us