-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbfstree.cpp
More file actions
43 lines (35 loc) · 763 Bytes
/
Copy pathbfstree.cpp
File metadata and controls
43 lines (35 loc) · 763 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include<bits/stdc++.h>
using namespace std;
int main(){
int node;
cin>>node;
vector<int>adj[node+1];
for(int i=1;i<node;i++){
int u,v;
cin>>u>>v;
adj[u].push_back(v);
adj[v].push_back(u);
}
for(int i=1;i<node;i++){
cout<<"for node number "<< i<<"- ";
for(int j=0;j<adj[i].size();j++){
cout<<adj[i][j]<<" ";
}
cout<<endl;
}
cout<<" traversing the tree BFS "<<endl;
queue<pair<int,int>>q;
q.push({1,0});
while(!q.empty()){
int nod = q.front().first;
int par = q.front().second;
q.pop();
cout<<nod<<" ";
for(int i=0;i<adj[nod].size();i++){
if(adj[nod][i]!=par){
q.push({adj[nod][i],nod});
}
}
}
return 0;
}