1004. Counting Leaves

题目链接: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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值