算法思想:先根遍历树,计算所有子树高度并记录最大者,最终整棵树的高度为最大者+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);
}
}
//算法思想:先根遍历树,计算所有子树高度并记录最大者,最终整棵树的高度为最大者+1
int getHeigh(CSTree T) {
if (T == NULL) {
return 0;
}
else {
int maxHeigh = 0;
for (CSTNode* pcurchild = T->firstchild; pcurchild != NULL; pcurchild = pcurchild->nextsibling) {
int pcurHeigh = getHeigh(pcurchild);//计算每棵子树高度
if (pcurHeigh > maxHeigh) {
maxHeigh = pcurHeigh;//记录子树高度最大值
}
}
return maxHeigh + 1;//子树高度最大者+1=树的高度
}
}
//124#5#6##37####
int main()
{
CSTree T = NULL;
creatCSTree(T);//建树
int heighCSTree = getHeigh(T);
printf("%d\n", heighCSTree);
return 0;
}