|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
#include <stdio.h>
#include <stdlib.h>
typedef char Elemtype;
typedef struct BiTreeNode
{
char data;
struct BiTreeNode *lchild,*rchild;
}BiTreeNode, *BiTree;
//创建二叉树
void CreateBiTree(BiTree &T)
{
char c;
scanf("%c",&c);
if('#'== c)
{
T = NULL;
}
else
{
T = (BiTreeNode *)malloc (sizeof(BiTreeNode));
T->data = c;
CreateBiTree(T->lchild);
CreateBiTree(T->rchild);
}
}
//访问二叉树结点
void visit(char c, int level)
{
printf("%c 在第 %d 层\n",c,level);
}
//前序遍历二叉树
void PreOrder(BiTree T,int level)
{
if(T)
{
visit(T->data,level);
PreOrder(T->lchild,level+1);
PreOrder(T->rchild,level+1);
}
}
//求叶子结点个数
void Number(BiTree T,int count)
{
if(T)
{
if(T->lchild == NULL && T->rchild ==NULL)
{
count++;
Number(T->lchild,count);
Number(T->rchild,count);
}
}
}
int main(void)
{
int level = 1;
int count = 0;
BiTree T;
CreateBiTree(T);
printf("前序遍历二叉树:\n");
PreOrder(T,level);
Number(T,count);
printf("二叉树叶子结点个数:%d\n",count);
getchar();
getchar();
getchar();
return 0;
}
这里的count输出一直是0,然后我改动了代码:
int Number(BiTree T,int count)
{
if(T)
{
if(T->lchild == NULL && T->rchild ==NULL)
{
count++;
Number(T->lchild,count);
Number(T->rchild,count);
}
}
return count;
}
main函数里是count = Number(T,count);这样还是0,不知道是哪里出错了,我们老师说计数器要用应用型参数,&count。但是我不太明白代码要怎么改动
哦哦,明白了,你是只统计叶子。
那么问题来了
- if(T->lchild == NULL && T->rchild ==NULL)
- {
- count++;
- count+=Number(T->lchild);
- count+=Number(T->rchild);
- }
复制代码
既然T->lchild == NULL,那么还有必要去调用Number(T->lchild)吗?
我认为应该是当该节点不是叶节点的时候才去进行递归调用吧?
不知道我有没有想错
- //Number函数实现过程如下
- int Number(BiTree T)
- {
- int count=0;
- if(T)
- {
- if(T->lchild == NULL && T->rchild ==NULL)
- count++;
- else
- {
- if (T->lchild)
- count+=Number(T->lchild);
- if (T->rchild)
- count+=Number(T->rchild);
- }
- }
- return count;
- }
- //主函数中的调用如下:
- count=Number(T);
复制代码
|
|