程序的输入是一个表示树结构的广义表。假设树的根为 root ,其子树森林 F = ( T1 , T2 , … , Tn ),设与该树对应的广义表为 L ,则 L =(原子,子表 1 ,子表 2 , … ,子表 n ),其中原子对应 root ,子表 i ( 1<i<=n )对应 Ti 。例如:广义表 (a,(b,(c),(d)),(f,(g),(h ),(i))) 表示的树如图所示:
程序的输出为树的层次结构、树的度以及各种度的结点个数。
在输出树的层次结构时,先输出根结点,然后依次输出各个子树,每个子树向里缩进 4 个空格,如:针对上图表示的树,输出的内容应为:
a
b
c
d
f
g
h
i
Degree of tree: 3
Number of nodes of degree 0: 5
Number of nodes of degree 1: 0
Number of nodes of degree 2: 2
Number of nodes of degree 3: 1
例: (下面的黑体为输入)
(a,(b),(c,(d),(e,(g),(h )),(f)))
a
b
c
d
e
g
h
f
Degree of tree: 3
Number of nodes of degree 0: 5
Number of nodes of degree 1: 0
Number of nodes of degree 2: 2
Number of nodes of degree 3: 1
C代码
#include<stdio.h>
int main() {
char inputChar, label[100]; //定义输入字符和标签数组
int count = 0, level[100], degree[100] = { 0 }, degreeCount[100] = { 0 }; //定义计数器、等级数组、度数组和度计数数组
int currLevel = -1, i, j, maxDegree = 0; //定义当前等级、循环变量和最大度
while (1)
{
inputChar = getchar();
if (inputChar == '\n') break;
switch (inputChar)
{
case '(': currLevel++; break; //左括号,当前等级增加
case ')': currLevel--; break; //右括号,当前等级降低
case ',': break; //逗号,不改变等级
default:
count++;
label[count] = inputChar;
level[count] = currLevel;
break; //其他字符,当作节点标签,将其存入数组,并标记其等级
}
}
//打印树状结构图
for (i = 1; i <= count; i++)
{
for (j = 0; j < level[i]; j++)
printf(" ");//对于每一层,打印相应的缩进
printf("%c\n", label[i]); //打印节点标签
}
//计算每个节点的度
for (i = 1; i <= count; i++)
{
for (j = i + 1; j <= count; j++)
{
if (level[j] == level[i]) break; //如果相同等级的节点出现,跳出
if (level[j] == level[i] + 1) //如果下一层级的节点出现,该节点的度加1
degree[i]++;
}
}
//找出最大的度
for (i = 1; i <= count; i++)
{
if (degree[i] > maxDegree)
maxDegree = degree[i];
}
//计算每个度的节点数
for (i = 1; i <= count; i++)
degreeCount[degree[i]]++;
//输出度和节点数
printf("Degree of tree: %d\n", maxDegree);
for (i = 0; i <= maxDegree; i++)
printf("Number of nodes of degree %d: %d\n", i, degreeCount[i]);
return 0;
}