PAT 1004

开始写的时候,不知道怎么判断 该层 有多少叶子结点
其实 queue中每次存的就是 该层的结点数
遍历的时候 不是用 pop 来直接循环,
而是用 queus.size() 来得到 该层结点个数 n
然后 用 for 循环遍历 n 完成该层的遍历



package com.promise.pat;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.Scanner;

public class T1004 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        // N为所有节点数,M为所有非叶节点数
        //Scanner的nextInt方法和nextLine不能混用!!
        String[] s=sc.nextLine().split(" ");
        int N = Integer.parseInt(s[0]), M = Integer.parseInt(s[1]);
        // 用一个ArrayList数组来保存每一个节点的子节点.节点从1开始,所以lists大小为N+1
        ArrayList<Integer>[] lists = new ArrayList[N + 1];
        for (int i = 0; i <= N; i++) {
            lists[i] = new ArrayList<Integer>();
        }
        // 循环读取输入
        for (int i = 0; i < M; i++) {
            // 将字符串以空格分割,结果为String数组
            String str=sc.nextLine();
            String[] strs = str.split(" ");
            for (int j = 2; j < strs.length; j++) {
                lists[Integer.parseInt(strs[0])].add(Integer.parseInt(strs[j]));
            }
        }
        // 广度优先搜索
        List<Integer> res = bfs(lists);

        for (int i = 0; i < res.size() - 1; i++) {
            System.out.print(res.get(i) + " ");
        }
        System.out.print(res.get(res.size() - 1));
    }

    private static List<Integer> bfs(ArrayList<Integer>[] lists) {
        // 树的层序遍历,需要借助队列完成
        Queue<Integer> queue = new LinkedList<Integer>();
        // res存储每层叶节点数
        List<Integer> res = new ArrayList<Integer>();
        queue.add(1);
        while (!queue.isEmpty()) {
            int count = 0, size = queue.size();
            //size 代表 该层上 子树的个数
            // 对每个子树进行遍历 ,查看 该子树 是否是 叶子结点
            for (int i = 0; i < size; i++) {
                int tmp = queue.poll();
                // 是叶子结点,加一
                if (lists[tmp].isEmpty()) {
                    count++;
                }
                // 不是叶子结点,将该节点的子树加入 queue, 构造下一层里面有哪些 结点
                else {
                    for (Integer num : lists[tmp])
                        queue.add(num);
                }

            }//对该层的所有结点遍历结束
            // res[i]  代表 第i层 有 res[i] 个叶子结点
            res.add(count);
        }//对所有层遍历结束
        return res;

    }

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值