二叉树各个节点的子节点之和(广搜版,要深搜的加我)

【题目描述】

求一棵二叉树的各个节点的子节点数量之和。

【输入输出样例】

输入:
 

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_♂

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值