题目信息
程序的输入是一个表示树结构的广义表。假设树的根为 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
测试样例
测试样例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
测试样例2
(a,(b,(c,(d),(e)),(f)),(g,(h),(i)),(j,(k,(m),(n),(o),(p,(r)))))
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))
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<iostream>
#define MAXN 100
using namespace std;
int main()
{
//freopen("/Users/zhj/Downloads/test.txt", "r", stdin);
string tmp;
cin >> tmp;
int len = tmp.length();
int num = 0;//用来记录出现的字母的数量
char ch[MAXN];//用来记录每个元素都是啥单词
int level[MAXN] = {0};//用来记录每个单词的深度
int depth = -1;//当前遍历的深度
for (int i = 0; i < len; i++)
{
if (tmp[i] == '(')
{
depth++;
}
else if (tmp[i] == ')')
{
depth--;
}
else if (tmp[i] == ',')
{
continue;
}
else
{
ch[num] = tmp[i];
level[num] = depth;
num++;
}
}
for (int i = 0; i < num; i++)
{
for (int j = 0; j < level[i]; j++)
{
cout << " ";
}
cout << ch[i] << endl;
}
int degree[MAXN] = {0};//每个字母的度
int Node[MAXN] = {0}; //每个度的字母数量
int max = 0;//最大度
for (int i = 0; i < num; i++)
{//为寻找到每个节点的度,需要两两之间相互一个一个进行遍历
for (int j = i + 1; j < num; j++)
{//仅从当前遍历的节点下一个进行遍历,这样才能叫同层次的遍历
if (level[j] == level[i])
{//当遍历到同层次的时候说明这一个平行节点已经遍历结束了,需要break掉了
break;
}
if (level[j] == level[i] + 1)
{//当遍历的节点恰好是下一节的节点,则给他的度加一,更深的节点不算是它的度
degree[i]++;
}
}
Node[degree[i]]++;
if (degree[i] > max)
{
max = degree[i];
}
}
cout << "Degree of tree: " << max << endl;
for (int i = 0; i <= max; i++)
{
cout << "Number of nodes of degree " << i << ": " << Node[i] << endl;
}
return 0;
}
想法
一个度为4的节点对应有4条出边,
一个度为3的节点对应有3条出边,
一个度为2的节点对应有2条出边,
一个度为1的节点对应有条出边,
叶子节点没有出边。
如例中:
a,b两点都有两个出边,故他们的度都为2
f点的出边有三个,所以他的度为3
其余点都为叶子节点没有出边,故他们的度为0