1004. Counting Leaves (30)
Input
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.
Output
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 Input2 1 01 1 02Sample Output
0 1
/**
作者:一叶扁舟
时间:21:36 2017/7/8
思路:统计树每一层结点的个数
*/
#include <stdio.h>
#include <stdlib.h>
#include <algorithm>
#include <stack>
#include <queue>
#include <math.h>
#include <string.h>
#include <vector>
using namespace std;
#define SIZE 100001
typedef struct TreeNode{
int data;
vector<int> child;
}TreeNode;
int level[SIZE] = { 0 };//定义每一层统计树节点数
//定义的树,可以用结构体,也可以用直接用vector<int> tree来定义
TreeNode treeNode[SIZE];
int IsRoot[SIZE] = { 0 };//0默认是根节点,1是子结点
//树的最大深度
int maxLevel = 0;
//得到每一层结点个数
void getLevelNodeNum(int rootNum, int depth){
//到了叶子节点
if (treeNode[rootNum].child.size() == 0){
level[depth]++;
if (depth > maxLevel){
maxLevel = depth;
}
return;
}
for (unsigned int i = 0; i < treeNode[rootNum].child.size(); i++){
//递归访问root的子结点
getLevelNodeNum(treeNode[rootNum].child[i], depth + 1);
}
}
int getTreeRoot(int N){
for (int i = 1; i <= N; i++){
if (IsRoot[i] != 1){
return i;
}
}
return 0;
}
int main(){
int N;
int m;//有孩子结点的个数
scanf("%d %d", &N, &m);
for (int i = 0; i < m; i++){
int num, nodeNo;//nodeNo父节点,num为父节点nodeNo后面的子结点的个数
scanf("%d %d", &nodeNo, &num);
for (int j = 0; j < num; j++){
int temp;
scanf("%d", &temp);
IsRoot[temp] = 1;//子结点再这里出现了,说明不可能是根节点
//存入对应的孩子结点
treeNode[nodeNo].child.push_back(temp);
}
}
//得到根结点
int rootNum = getTreeRoot(N);
getLevelNodeNum(rootNum, 1);
double result = 0;
//输出每一层的结点个数
for (int i = 1; i <= maxLevel; i++){
//找到depth大于0的
printf("%d",level[i]);
if (i != maxLevel){
printf(" ");
}
}
system("pause");
return 0;
}