第1个回答 2019-08-16
/******************************************************/
/*
二叉树的建立深度优先遍历求叶子个数求深度
*/
/******************************************************/
#include
"stdio.h"
#include
"string.h"
#include
"stdlib.h"
#define
null
0
typedef
struct
bitnode{
int
data;
struct
bitnode
*lchild,*rchild;
}bitnode,*bitree;
/*创建一个二杈树以#号结束*/
bitree
create(bitree
t){
char
ch;
ch=getchar();
if(ch=='#')
t=null;
else{
t=(bitree)malloc(sizeof(bitnode));
t->data=ch;
t->lchild=create(t->lchild);
t->rchild=create(t->rchild);
}
return
t;
}
/*递归遍历*/
void
preorder(bitree
t){
if(t){
printf("%c",t->data);
/*先序*/
preorder(t->lchild);
/*printf("%c",t->data);
中序*/
preorder(t->rchild);
/*printf("%c",t->data);
后序*/
}
}
/*求深度*/
int
depth(bitree
t){
int
depthval,depl,depr;
if(!t)
depthval=0;
else{
depl=depth(t->lchild);
depr=depth(t->rchild);
depthval=1+(depl>depr?depl:depr);
}
return
depthval;
}
/*求叶子数*/
int
countleaf(bitree
t){
int
count=0;
if(!t)
count=0;
else
if((!t->lchild)&&(!t->rchild))
count++;
else
count=countleaf(t->lchild)+countleaf(t->rchild);
return
count;
}
/*主函数*/
main(){
bitree
t=null;
printf("\nplease
input
a
tree:");
t=create(t);
preorder(t);
printf("\ndepth:%d\nleave:%d\n",depth(t),countleaf(t));
system("pause");
}
程序以调试通过!!!!!