【题目描述】
求一棵二叉树的各个节点的子节点数量之和。
【输入输出样例】
输入:
5 2 3 4 5 0 0 0 0 0 0
输出:
4 2 0 0 0
【解题技巧】
广搜就是while加队列,比深搜好理解一些,注释如下。
【源代码】
#include<bits/stdc++.h>
#include<iostream>
#include<cstdio>
#include<cstring>
#include<iomanip>
#include<cmath>
#include<algorithm>
#include<vector>
#include<map>
#include<set>
#include<queue>
using namespace std;
int a[1010][2];
int n,ans;//变量跟深搜类似
void bfs(int x){
queue<int> q;
q.push(x);
//一开始将起点归入队列
while(!q.empty()){//非空才能继续
int f=q.front();
q.pop();
//取出并存储队首元素,队首元素没有价值,出队列
if(a[f][0]){
ans++;
q.push(a[f][0]);
}
if(a[f][1]){
ans++;
q.push(a[f][1]);
}//用队首元素找下一代子节点,找到的全都归入队列
}
}
int main(){
scanf("%d",&n);
for(int i=1;i<=n;i++){
scanf("%d%d",&a[i][0],&a[i][1]);
}
for(int i=1;i<=n;i++){
ans=0;
bfs(i);
printf("%d ",ans);//输出每轮的结果ans
}
return 0;
}
//♂_The_LYH_25_♂