对以孩子-兄弟链表表示的树编写计算深度的算法。
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <malloc.h>
using namespace std;
typedef struct tnode
{
int data;
struct tnode *child,*brother;
}tnode,*bitree;
void creattree(bitree &bt)
{
char ch;
scanf("%c",&ch);
getchar();
if(ch=='#')
bt=NULL;
else
{
bt=(tnode*)malloc(sizeof(tnode));
bt->data=ch;
printf("输入%c的孩子结点:",ch);
creattree(bt->child);
printf("输入%c的兄弟结点:",ch);
creattree(bt->brother);
}
}
int tdepth(bitree t)
{
int h1,h2;
if(!t)
{
return 0;
}
else
{
h1=1+tdepth(t->child);
h2=tdepth(t->brother);
return h1>h2?h1:h2;
}
}
int main()
{
bitree bt;
int k;
bt=(tnode*)malloc(sizeof(tnode));
printf("输入根节点:");
creattree(bt);
k=tdepth(bt);
printf("%d\n",k);
return 0;
}