2.树的建立与基本操作
程序的输入是一个表示树结构的广义表。假设树的根为 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
思路浅析
这道题我用的是比较投机取巧的方法, 通过数层数的方法直接输出树的结构,通过记录每一个左括号实现深度的变化和度的记录,通过记录右括号实现了把记录度的数组清零的功能。一开始我自己写的比较乱,之后借鉴了另一个帖子的思路(https://www.jianshu.com/p/3e646897b0ed),重新写了一遍。
#include <stdio.h>
#include <string.h>
#define MAXSIZE 10000
int main()
{
char s[MAXSIZE];
int degree = 0, depth = -1, temp[100] = {0}, num[100] = {0};
scanf("%s", &s);
int len = strlen(s);
int left = 0;
for (int i = 0; i < len; i++)
{
if (s[i] == ',' || s[i] == ' ')
continue;
else if (s[i] == '(')//读到左括号,深度加一,度加一
{
left = 1;
if (depth != -1)
temp[depth]++;
depth++;
continue;
}
else if (s[i] == ')')//读到右括号,深度减一,记录当前度
{
if (depth > -1)
{
if (!left)
num[temp[depth]]++;
if (temp[depth] > degree)
degree = temp[depth];
temp[depth] = 0;
depth--;
}
else
break;
continue;
}
else//读到字符,根据深度输出
{
if (left)
left = 0;
for (int j = 0; j < depth; j++)
printf(" ");
printf("%c\n", s[i]);
}
}
printf("Degree of tree: %d\n", degree);
for (int i = 0; i <= degree; i++)
printf("Number of nodes of degree %d: %d\n", i, num[i]);
return 0;
}