A family hierarchy is usually presented by a pedigree tree. Your job is to count those family members who have no child.
Input Specification:
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.
The input ends with N being 0. That case must NOT be processed.
Output Specification:
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
思路:用广度优先搜索进行层序遍历,也可使用深度优先搜索,似乎更简单,
层序遍历版本:
//Counting Leaves
#include <iostream>
#include <queue>
#include <algorithm>
#include <cstring>
using namespace std;
//思路,结构体建树
struct node
{
int father; //记录他的父亲结点的序号
int depth; //记录该节点的深度
int son; //代表他是否有儿子
}P[105];
queue<int> q;
int n,m;
int nums[105];
void Build()
{
//先找到根节点入队列
for(int i = 1;i<=n;i++)
{
if(P[i].father==-1)
{
q.push(i);
}
}
while(!q.empty()) //当不为空时执行
{
int u = q.front(); //弹出标号
q.pop();
//寻找以u为父节点的根节点
for(int i = 1;i<=n;i++)
{
if(P[i].father==u)
{
P[i].depth = P[u].depth + 1;
q.push(i); //入队列
}
}
}
return;
}
int main()
{
cin>>n>>m;
int x,num;
for(int i = 1;i<=n;i++)
{
P[i].depth = 0;
P[i].father =-1;
P[i].son = 0;
}
memset(nums,0,sizeof(nums));
for(int i = 0;i<m;i++)
{
scanf("%d",&x);
scanf("%d",&num);
if(num>0)
P[x].son = 1; //表示他有儿子
int y;
for(int j =0;j<num;j++)
{
scanf("%d",&y);
P[y].father = x; //他们的父亲标记为x
}
}
Build(); //建树操作
int maxdepth=0;
for(int i = 1;i<=n;i++)
{
if(P[i].depth>maxdepth)
maxdepth = P[i].depth;
if(P[i].son==0)
nums[P[i].depth]+=1;
}
int k = 0;
printf("%d",nums[k]);
k+=1;
while(k<=maxdepth)
{
printf(" %d",nums[k]);
k+=1;
}
return 0;
}
深度优先的思路就是当遍历到某一结点无孩子的时候,就nums【该节点的层数】++;