题目链接:http://pat.zju.edu.cn/contests/pat-a-practise/1004
树的遍历,而非二叉树的遍历。采用孩子兄弟表示法,进行DFS。
如果使用邻接表,构建树时相对简单些。
// 使用孩子兄弟表示法
// 深度遍历
#include <stdio.h>
#define SIZE 200+5
struct Node{
int c;// chile
int b;// brother
};
int n, m;
Node tree[SIZE];
int count[SIZE];// 每层叶子节点数
void Init()
{
int i;
for(i=1; i<=n; i++)
{
tree[i].c=NULL;
tree[i].b=NULL;
count[i]=0;// n个节点,深度不会超过n
}
return ;
}
void dfs(Node* T, int h, int &maxhigh)
{
if(T->c == NULL)
{
count[h]++;
maxhigh = maxhigh > h ? maxhigh:h;
}
else
{
dfs(&tree[T->c], h+1, maxhigh);
}
if(T->b != NULL)
{
dfs(&tree[T->b], h, maxhigh);
}
return ;
}
int main()
{
#ifdef ONLINE_JUDGE
#else
freopen("E:\\in.txt", "r", stdin);
#endif
scanf("%d%d", &n, &m);
Init();
int i;
for(i=0; i<m; i++)
{
int k;
int id;
scanf("%d%d", &id, &k);
int j, prechild;
for(j=1; j<=k; j++)
{
if(1==j)
{
scanf("%d", &prechild);
tree[id].c = prechild;
}
else
{
scanf("%d", &tree[prechild].b);
prechild = tree[prechild].b;
}
}// 构造孩子兄弟树
}
int high=1, maxhigh=1;
Node *T = &tree[1];
dfs(T, high, maxhigh);
for(i=1; i<maxhigh; i++)
{
printf("%d ", count[i]);
}
printf("%d\n", count[i]);
return 0;
}