树的分析:pat1004求叶子结点

1004 Counting Leaves (30)(30 分)
A family hierarchy is usually presented by a pedigree tree. Your job is to count those family members who have no child.

Input

Each input file contains one test case. Each case starts with a line containing 0 < N < 100, the number of nodes in a tree, and M (< N), the number of non-leaf nodes. Then M lines follow, each in the format:

ID K ID[1] ID[2] … ID[K]
where ID is a two-digit number representing a given non-leaf node, K is the number of its children, followed by a sequence of two-digit ID’s of its children. For the sake of simplicity, let us fix the root ID to be 01.

Output

For each test case, you are supposed to count those family members who have no child for every seniority level starting from the root. The numbers must be printed in a line, separated by a space, and there must be no extra space at the end of each line.

The sample case represents a tree with only 2 nodes, where 01 is the root and 02 is its only child. Hence on the root 01 level, there is 0 leaf node; and on the next level, there is 1 leaf node. Then we should output “0 1” in a line.

Sample Input

2 1
01 1 02
Sample Output
0 1
题目大意:给出一颗树的非叶子节点以及该节点的孩子,求出每一层的叶子节点个数
这题的思路比较简单,采用BFS的算法来做

压入每个节点及其孩子
queue  m;
m.push(1);将头节点压入
while(!m.empty())
{
    取出队列首个元素
    队列第一个元素出队
    for(循环出队元素的孩子)
    {
        该孩子的层数 = 父亲层数+1;
        放入队列
    }
    如果该节点的孩子为空
    相应层数+1
}
输出每一层对应的叶子节点
ac代码如下:
#include  <iostream>
#include  <cstdio>
#include  <algorithm>
#include  <vector>
#include  <queue>
using  namespace  std;
struct  node
{
    int  data;
    int  level;
};
vector<node>  tree[101];
int  main()
{
    int  nodes,nonnode;
    scanf("%d %d",&nodes,&nonnode);
    int  data;
    for(int  i=0;i<nonnode;i++)
    {
        int  num;
        node  u;
        scanf("%d %d",&data,&num);
        for(int  j=0;j<num;j++)
        {
            scanf("%d",&u.data);
            tree[data].push_back(u);
        }
    }
    node  head;
    head.data = 1;
    head.level = 0;
    int  levels[10010];
    fill(levels,levels+10010,0);
    //levels记录每一层的叶子节点数
    queue<node>  m;
    m.push(head);
    //头节点压入队列
    int  num=0;
    while(!m.empty())
    {
        node  j=m.front();
        m.pop();
        for(int  i=0;i<tree[j.data].size();i++)
        //遍历节点j的孩子节点
        {
            tree[j.data][i].level = j.level +1;
            num = j.level +1;
            m.push(tree[j.data][i]);
        }
        if(tree[j.data].size() == 0)
        //如果该节点为孩子节点,对应的叶子节点的层数加1
        {
            levels[j.level] ++;
        }
    }
    for(int  i=0;i<=num;i++)
    {
        if(i!=0)
        {
            printf(" ");
        }
        printf("%d",levels[i]);
    }
    return  0;
}
发布了17 篇原创文章 · 获赞 7 · 访问量 3004

猜你喜欢

转载自blog.csdn.net/znevegiveup1/article/details/81482088