PAT甲级-1004. Counting Leaves (30)-树的叶结点个数-DFS

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

思路:本题要求数出树的每个层次上的叶结点个数,可用DFS对结点进行遍历,同时附上结点的所在的层数,并用数组depth[i]记录层次i的叶结点个数。当判断某个结点是叶结点时,就将其所在层树的数组元素加1。

#c++代码
#include<cstdio>
#include<vector>
#include<algorithm>
using namespace std;

/*题目所需所有常量与变量:n=点数,maxn=点的最大编号-1,e=边数*/
const int maxn = 110;
int n, e;

/*关于点的变量:no[i](node的缩写)存储结点i的所有孩子,v[i](visit的缩写)记录点i是否被访问过*/
vector<int> no[maxn];
int v[maxn];

/*关于树的变量:depth[i]记录树的第i层的叶子结点个数;maxd记录树的最大层数*/
int depth[maxn];
int maxd;

/*用DFS遍历结点,更新最大的层数,并记录叶结点的个数*/
void DFS(int cur, int d) {    
/*cur为当前遍历的结点,d为cur所在的层数*/
    if (d > maxd)maxd = d;   
/*若当前结点cur所在的层数更大,则更新*/
    if (no[cur].size() == 0) {  
        depth[d]++;    
        return; 
    }
/*若当前结点cur为叶结点,则其所在层数d的叶结点个数depth[d]增加*/
    for (int i = 0; i < no[cur].size(); i++) {
        int id = no[cur][i];
        DFS(id, d + 1);
    }
/*若当前结点cur为非叶结点,则继续遍历它的孩子结点*/
}

int main() {
/*接收所有数据*/
    scanf("%d %d", &n, &e);
    for (int i = 0; i < e; i++) {
        int in1, k;
        scanf("%d %d", &in1, &k);
        for (int j = 0; j < k; j++) {
            int in2;
            scanf("%d", &in2);
            no[in1].push_back(in2);
        }
    }
/*初始化数据*/
    maxd = 0;
/*DFS的入口为根结点01,其位于0层*/
    DFS(1, 0);
/*打印[0,maxd]层的叶子结点个数*/
    printf("%d", depth[0]);
        for (int i = 1; i <= maxd; i++) {
            printf(" %d", depth[i]);
    }

    return 0;
}

猜你喜欢

转载自blog.csdn.net/yeziand01/article/details/80738783