PAT Advanced Level 1004 Counting Leaves
1. 题目简述及在线测试位置
1.1 已知树的结点总数、非叶结点总数 以及 每个非叶结点的所有子结点编号(根结点编号定为01),要求统计出每一层的叶结点(数叶子)
1.2 在线测试位置:1004 Counting Leaves
2. 基本思路
2.1 数据结构 通过vector数组存储树:数组下标对应结点编号,数组元素值对应该结点下的所有子结点
#define MAX 100
vector<int> TreeNode[MAX];
2.2 通过 层序遍历 遍历整个树,通过数组RecordLeafNum记录各层的叶结点数:叶结点对应 TreeNode[Node].size() = 0 ;由于层序遍历本身无法定位当前层,因此引入数组Level记录各个结点所在的层(根结点所在层定为第一层)
void LevelOrder()
{
int root = 1,Node;
queue<int> q;
q.push(root);
Level[root] = 1; //定义根结点所在为1层
while (!q.empty())
{
Node = q.front();
q.pop();
if (!TreeNode[Node].size()) //叶结点
RecordLeafNum[Level[Node]]++;
else
{
for (int i = 0; i < TreeNode[Node].size(); i++)
{
q.push(TreeNode[Node][i]);
Level[TreeNode[Node][i]] = Level[Node] + 1;
}
}
}
return;
}
2.3 层序遍历结束后,统计出最大层 并 打印各层的叶结点数量
short MaxLevel=1; //树的最大层
for (int i = 1; i <= NodeNum; i++)
if (Level[i] > MaxLevel)
MaxLevel = Level[i];
cout << RecordLeafNum[1]; //打印各层的叶结点数量
for (int i = 2; i <= MaxLevel; i++)
cout << " " << RecordLeafNum[i];
3. 完整AC代码
#include <queue>
#include <vector>
#include <iostream>
using namespace std;
#define MAX 100
vector<int> TreeNode[MAX]; //通过vector数组记录树:数组下标对应结点编号,数组值对应该结点下的子结点
short Level[MAX] = {0}; //各结点所在层
short RecordLeafNum[MAX]; //记录各层的叶结点数量
void LevelOrder();
int main()
{
int NodeNum, NotLeafNum;
cin >> NodeNum >> NotLeafNum;
for(int i=0;i<NotLeafNum;i++)
{
int Parent, ChildNum, Child;
cin >> Parent >> ChildNum;
for (int i = 0; i < ChildNum; i++)
{
cin >> Child;
TreeNode[Parent].push_back(Child);
}
}
LevelOrder();
short MaxLevel=1; //树的最大层
for (int i = 1; i <= NodeNum; i++)
if (Level[i] > MaxLevel)
MaxLevel = Level[i];
cout << RecordLeafNum[1]; //打印各层的叶结点数量
for (int i = 2; i <= MaxLevel; i++)
cout << " " << RecordLeafNum[i];
return 0;
}
void LevelOrder()
{
int root = 1,Node;
queue<int> q;
q.push(root);
Level[root] = 1; //定义根结点所在为1层
while (!q.empty())
{
Node = q.front();
q.pop();
if (!TreeNode[Node].size()) //叶结点
RecordLeafNum[Level[Node]]++;
else
{
for (int i = 0; i < TreeNode[Node].size(); i++)
{
q.push(TreeNode[Node][i]);
Level[TreeNode[Node][i]] = Level[Node] + 1;
}
}
}
return;
}