多叉树层序遍历+统计多叉树叶节点 1004 Counting Leaves (30分)

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

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

解题
给出多叉树非叶节点的子节点,统计每一层的叶节点的数量并输出;

1.输入函数
因为给的数据为每个结点的子节点,所以链式储存每个结点的子节点较好;
故用vector 类型;

#include
#include
#include
using namespace std;

vector<vector<int>> Tree(101);

int N,M; 

void input()
{
	cin>>N>>M;
	int K;
	int ID;
	int tmp; 
	for(int i=0;i<M;i++)
	{
		cin>>ID>>K;
		for(int j=0;j<K;j++)
			{
				cin>>tmp;
				Tree[ID].push_back(tmp);
			}
	}
	//此时Tree中每个点保存了该结点的子树下标; 
}

2.遍历多叉树
因为要求每一层的叶节点数,故使用层序遍历更好;
构建队列,层层入队,出队时判断出队的元素是否为层尾,若是则统计该层的叶节点数,存入结果数组中;
若出队元素没有子节点,则该层叶节点数+1;

vector<int> result;
void Traverse()
{
	queue<int> T;
	T.push(1);
	//计算每一层的叶节点数
	int Leaf=0;    //统计每一层的个数 
	int End=1;    //指向当前出队层的最后一个 
	int temp;  //指向入队那层的最后一个 
	
	while(!T.empty())
	{
		int a=T.front();
		T.pop();

		if(Tree[a].size()==0) ++Leaf;
		//先把a的子树入队 
		else 
		{
			for(int i=0;i<Tree[a].size();i++)
				T.push(Tree[a][i]);
			temp = Tree[a][Tree[a].size()-1];
		}
		
		if(a==End){
			result.push_back(Leaf);
			End=temp;
			Leaf=0;
		}
	}
}

3.main函数
按规则暑促和结果列表即可

int main()
{
	input();
	Traverse();
	if(result.size()>0)
	cout<<result[0];
	for(int i=1;i<result.size();i++)
		cout<<" "<<result[i];
 } 

总结
多叉树的子树需要链式结构储存,按层遍历多叉树用层序遍历较好;
层序遍历同时需要

	int End=1;    //指向当前出队层的最后一个 
	int temp;  //指向入队那层的最后一个 

两个变量辅助;

你可能感兴趣的:(PAT,数据结构,树)