根节点T的孩子数量=1个孩子结点+孩子结点的所有兄弟结点.
算法思想:先根遍历树,访问树中每一个结点并计算每个结点的孩子数,孩子结点数量最大者即为树的度.
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef char ElemType;
typedef struct CSTNode {
ElemType data;
struct CSTNode* firstchild;
struct CSTNode* nextsibling;
}CSTNode, * CSTree;
//先序创建孩子兄弟链表
void creatCSTree(CSTree& T) {
ElemType ch;
scanf("%c", &ch);
if (ch == '#') {//#代表空结点
T = NULL;
}
else {
T = (CSTNode*)malloc(sizeof(CSTNode));
T->data = ch;
creatCSTree(T->firstchild);
creatCSTree(T->nextsibling);
}
}
//根节点T的孩子数量=1个孩子结点+孩子结点的所有兄弟结点
//算法思想:先根遍历树,访问树中每一个结点并计算每个结点的孩子数,孩子结点数量最大者即为树的度
int getDegree(CSTree T) {
if (T == NULL) {
return 0;
}
else {
int rootleavesNum = 0;
int maxleavesNum = 0;
for (CSTNode* pcurchild = T->firstchild; pcurchild != NULL; pcurchild = pcurchild->nextsibling) {
rootleavesNum += 1;//根结点的度
int pcurleavesNum=getDegree(pcurchild);//子树的度
if (pcurleavesNum > maxleavesNum) {//保留子树中最大值
maxleavesNum = pcurleavesNum;
}
}
//根节点与子树中度的最大值即为整棵树的度
return rootleavesNum > maxleavesNum ? rootleavesNum : maxleavesNum;
}
}
//124#5#6##37####
int main()
{
CSTree T = NULL;
creatCSTree(T);//建树
int degreeCSTree = getDegree(T);
printf("%d\n", degreeCSTree);
return 0;
}