queue.empty() //为空则返回真;
树的层序遍历
没用递归,,为什么我一直觉得只有用了递归才算遍历,,
#include <cstdio>
#include <iostream>
#include <cstdlib>
#include <vector>
#include <algorithm>
#include <queue>
using namespace std;
vector<int> arr[100];
int main(){
int N, M;
cin >> N >> M;
for(int i=0 ; i<M; i++){
int t, k;
cin >> t >> k;
for(int j=0; j<k; j++){
int h;
//cin >> arr[t][j]; 这个地方这么写读不进去,,
arr[t].push_back(h);
}
}
queue<int> que;
que.push(1);
int sum = 1, last = 0, ans = 0;
bool first = true;
while(!que.empty()){
sum--;
int t = que.front();
que.pop();
if(arr[t].size()==0) ans++;
else{
last += arr[t].size();
for(int l=0; l<arr[t].size(); l++){
que.push(arr[t][l]);
}
}
if(sum==0){
if(first){
printf("%d",ans);
first = false;
}
else printf(" %d",ans);
sum = last;
last = ans = 0;
}
}
return 0;
}