程序的输入是一个表示树结构的广义表。假设树的根为 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
样例
输入(1)
(a,(b),(c,(d),(e,(g),(h)),(f)))
输出(1)
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
输入(2)
(a,(b,(c,(d),(e)),(f)),(g,(h),(i)),(j,(k,(m),(n),(o),(p,(r)))))
输出(2)
a
b
c
d
e
f
g
h
i
j
k
m
n
o
p
r
Degree of tree: 4
Number of nodes of degree 0: 9
Number of nodes of degree 1: 2
Number of nodes of degree 2: 3
Number of nodes of degree 3: 1
Number of nodes of degree 4: 1
输入(3)
(a,(b),(c),(d,(m),(n)),(e,(o)),(f),(h))
输出(3)
a
b
c
d
m
n
e
o
f
h
Degree of tree: 6
Number of nodes of degree 0: 7
Number of nodes of degree 1: 1
Number of nodes of degree 2: 1
Number of nodes of degree 3: 0
Number of nodes of degree 4: 0
Number of nodes of degree 5: 0
Number of nodes of degree 6: 1
代码
#include <stdio.h>
int main() {
char c, ab[100];
int num = 0, level[100], degree[100] = {0}, p[100] = {0}; //字母数量,每个字母的级别,每个字母的度,每个度的字母数量
int depth = -1, i, j, max = 0;
while (1) {
c = getchar();
if (c == '\n') break;
switch (c) {
case '(':
depth++;
break;
case ')':
depth--;
break;
case ',':
break;
default:
num++;
ab[num] = c;
level[num] = depth;
break;
}
}
// Print the tree structure
for (i = 1; i <= num; i++) {
for (j = 0; j < level[i]; j++) printf(" ");
printf("%c\n", ab[i]);
}
// Calculate the degree of each node
for (i = 1; i <= num; i++) {
for (j = i + 1; j <= num; j++) {
if (level[j] == level[i]) break;
if (level[j] == level[i] + 1) degree[i]++;
}
}
// Find the maximum degree
for (i = 1; i <= num; i++) {
if (degree[i] > max) max = degree[i];
}
// Count the nodes with each degree
for (i = 1; i <= num; i++) p[degree[i]]++;
// Print the results
printf("Degree of tree: %d\n", max);
for (i = 0; i <= max; i++) printf("Number of nodes of degree %d: %d\n", i, p[i]);
return 0;
}