#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
//二叉树的存储结构,一个数据域,2个指针域
typedef struct tree
{
char data;//数据域
struct tree *lchild;//左子节点
struct tree *rchild;//右子节点
}Bitree;
//创建一棵二叉树
Bitree *CreateBitree()
//返回值为Bitree类型的名为CreateBitree的函数,传入参数为Bitree类型的T的地址
{ Bitree *T;
char ch;
scanf("%c",&ch);
if(ch=='$')
return NULL;//若输入为空,结点为空
else
//若不为空,创建结点
{
T=(Bitree *)malloc(sizeof(Bitree));//分配存储空间
T->data=ch;
T->lchild=CreateBitree();
T->rchild=CreateBitree();
return T;
}
}
//递归实现二叉树的深度
int treedepth(Bitree *T)
{
int rd=0,ld=0;
if(T!=NULL)
{
//找到最左边的左右孩子为空的结点,之后找到相对位置靠近第一个结点的结点
ld=treedepth(T->lchild)+1;
rd=treedepth(T->rchild)+1;
}
return ld>=rd?ld:rd;//取左右深度最大值为二叉树的深度
}
int main(void)
{
Bitree *T;//创建根节点
//printf("请以先序输入二叉树($表示该结点的子结点为空):\n");
T=CreateBitree();
int deep=treedepth(T);//创建整形变量deep调用treedepth函数,将二叉树T传过去
printf("%d\n",deep);
}