注意事项:
- 树的表示方法分为:双亲表示法、孩子表示法、孩子兄弟表示法(二叉链表表示法),目前只涉及二叉链表(孩子兄弟)表示法的森林表示法。
- 由于森林的二叉链表不知道孩子的数量,所以不能使用递归建立,而使用队列辅助建立。
#include<stdio.h>
#include<string.h>
#include<malloc.h>
#include<stdlib.h>
typedef struct CSNode
{
char data;
struct CSNode * firstchild, *nextsibling;
}CSNode, *CSTree;
void CreatTree(CSTree *t)
{
char c[20];
CSTree p, p1;
LinkQueue q;
int i, m;
initQueue(q);
printf("请输入根结点:");
scanf_s("%c% * c", &c[0]);
if (c[0] != NULL)
{
*t = (CSTree)malloc(sizeof(CSNode));
(*t)->data = c[0];
(*t)->nextsibling = NULL;
EnQueue(q, t);
while (!QueueEmpty(q))
{
DeQueue(q, p);
printf("按照长幼顺序输入结点%c所有的孩子:", p->data);
gets(c);
m = strlen(c);
if (m > 0)
{
p1 = p->firstchild = (CSTree)malloc(sizeof(CSNode));
p1->data = c[0];
EnQueue(q, p1);
for (i = 1; i < m; i++)
{
p1->nextsibling = (CSTree)malloc(sizeof(CSNode));
p1 = p1->nextsibling;
p1->data = c[i];
EnQueue(q, p1);
}
p1->nextsibling = NULL;
}
else
p->firstchild = NULL;
}
}
else
t = NULL;
}
int TreeDepth(CSTree t)
{
CSTree p;
int depth, max = 0;
if (!t)
return 0;
for (p = t->firstchild;p;p = p->nextsibling)
{
depth = TreeDepth(p);
if (depth > max)
max = depth;
}
return max + 1;
}