pat甲级1004Counting Leaves(c语言版)

该代码片段展示了如何利用队列数据结构实现层次遍历,统计二叉树中每一层的叶子结点数量。程序首先初始化树结构,然后使用队列存储当前层的节点,逐层遍历直到遍历完整棵树。
摘要由CSDN通过智能技术生成
#include<stdio.h>
//问每一层多少叶子结点
struct TreeNode{
    int id=0;//结点编号
    int childCount=0;//孩子数量,为零即叶子
    int children[100]={0};//孩子结点编号数组
};
struct TreeNode tree[100];
int main(){
    int n,m;
    scanf("%d",&n);
    if(n!=0){
    	for(int i=0;i<100;i++){
    		tree[i].id=i;
    	} 
        scanf("%d",&m);
        for(int i=0;i<m;i++){
            int id,childCount;
            scanf("%d %d",&id,&childCount);
            tree[id].id=id;
            tree[id].childCount=childCount;
            for(int j=0;j<childCount;j++){
                int children;
                scanf("%d",&children);
                tree[id].children[j]=children;
            }
        }
        //每一层多少个叶子结点,难道不应该层序遍历吗?
        //我需要一个队列
        TreeNode quene[100];
        int front=0,rear=0;
        TreeNode root=tree[1];
        quene[rear]=root;//后面进,前面出
        rear++;
        while(front<rear){
            for(int i=0;i<quene[front].childCount;i++){
                quene[rear]=tree[quene[front].children[i]];//其实就是插入num=quene[front].children[i]的树 
                rear++;
            }
            front++;
        }
        int p=0;//从根节点开始遍历
        int leafCount=0;//叶子数量
        //我需要记录这一层的最后一个结点,还要记录这一层最后一个有孩子的结点!,应该是上一层最后一个(有孩子的)结点的最后一个孩子就是这一层最后一个结点!
        TreeNode thisLast,lastLast;
        int lastParent=0;//上一层最后一对父母
        thisLast=root;//这一层最后就是root
        while(p!=n){//n是总结点数
            if(p!=0)
                printf(" ");
            leafCount=0;
            while(quene[p].id!=thisLast.id){
                if(quene[p].childCount==0){
                    leafCount++;
                }else{
                    lastParent=p;
                }
                p++;
            }
            if(quene[p].childCount==0){//此时quene[p]==thisLast
                leafCount++;
            }else{
                lastParent=p;
            }
            p++;
            printf("%d",leafCount);
            lastLast=quene[lastParent];
            thisLast=tree[lastLast.children[lastLast.childCount-1]];
        }            
    }
    return 0;
}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值