求二叉树的叶子结点个数的代码 错在哪啊?

WellerV 2012-05-17 08:44:04
#include<stdio.h>
#include<string.h>
typedef char ElemType ;
int sum=0;

typedef struct BiTNode
{
ElemType data;
struct BiTNode *Lchild,*Rchild;
}BiTNode,*BiTree;

BiTree Create(BiTree T)
{
char ch;
ch=getchar();
if(ch==' ') T=NULL;
else
{
if(!(T=(BiTNode *)malloc(sizeof(BiTNode)))) printf("error.\n");
T->data=ch;
T->Lchild=Create(T);
T->Rchild=Create(T);
}
return T;
}

void Preorder(BiTree T)
{
if(T)
{
printf("%c",T->data);
Preorder(T->Lchild);
Preorder(T->Rchild);
}
}



//无子树的结点设为0,叶子结点设为1,其他是子树的叶子结点之和。

int Sumleaf(BiTree T)
{
if(T)
{
if(T==NULL) sum=0;
else if(T->Lchild==NULL&&T->Rchild==NULL) sum=1;
else sum=Sumleaf(T->Lchild)+Sumleaf(T->Rchild);
return sum;
}
}

int depth(BiTree T)
{
int hl,hr;
if(T)
{
hl=depth(T->Lchild);
hr=depth(T->Rchild);
return 1+(hl>hr?hl:hr);
}
else return 0;
}
void main()
{
BiTree T;
T=Create(T);
Preorder(T);
printf("\n%d\n",Sumleaf(T));
printf("%d\n",depth(T));
}


还有个问题,可以系统的解释下*&p是不是就是等于p啊
...全文
284 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
WellerV 2012-05-17
  • 打赏
  • 举报
回复
vc6.0啊 输入 是按你说的输的 可是结果还是不对哦
W170532934 2012-05-17
  • 打赏
  • 举报
回复

typedef char ElemType ;
int sum=0;

typedef struct BiTNode
{
ElemType data;
struct BiTNode *Lchild,*Rchild;
}BiTNode,*BiTree;

BiTree Create(BiTree T)
{
char ch;
ch=getchar();
getchar();
if(ch==' ') T=NULL;
else
{
if(!(T=(BiTNode *)malloc(sizeof(BiTNode)))) printf("error.\n");
T->data=ch;
T->Lchild=Create(T);
T->Rchild=Create(T);
}
return T;
}

void Preorder(BiTree T)
{
if(T)
{
printf("%c",T->data);
Preorder(T->Lchild);
Preorder(T->Rchild);
}
}



//无子树的结点设为0,叶子结点设为1,其他是子树的叶子结点之和。

int Sumleaf(BiTree T)
{
if(T)
{
if(T==NULL) sum=0;
else if(T->Lchild==NULL&&T->Rchild==NULL) sum=1;
else sum=Sumleaf(T->Lchild)+Sumleaf(T->Rchild);
return sum;
}
}

int depth(BiTree T)
{
int hl,hr;
if(T)
{
hl=depth(T->Lchild);
hr=depth(T->Rchild);
return 1+(hl>hr?hl:hr);
}
else return 0;
}
void main()
{
BiTree T;
T=Create(T);
Preorder(T);
printf("\n%d\n",Sumleaf(T));
printf("%d\n",depth(T));
}


改好了,输入的时候应该是输入空格键然后回车才能确保是结束NULL
W170532934 2012-05-17
  • 打赏
  • 举报
回复
敢问楼主是怎么输入的?你是什么编译器,我这都是测试好的才发过来的。
WellerV 2012-05-17
  • 打赏
  • 举报
回复
谢谢啊 不行 你改了 不但 二叉树的建立变复杂啦,而且求出的叶子结点数还是一个错误的数

33,311

社区成员

发帖
与我相关
我的任务
社区描述
C/C++ 新手乐园
社区管理员
  • 新手乐园社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧