统计二叉树中叶子结点个数的问题,
#include <stdio.h>#include <stdlib.h>
typedef struct Node
{
int data;
struct Node *LChild;
struct Node *RChild;
}BiTNode,*BiTree;
int Leaf_Count;
//先序遍历创建二叉树
void CreateBiTree(BiTree *bt)
{
int ch;
scanf("%d",&ch);
if(ch==0)
*bt=NULL;
else
{
*bt=(BiTree)malloc(sizeof(BiTree));
(*bt)->data=ch;
CreateBiTree(&((*bt)->LChild));
CreateBiTree(&((*bt)->RChild));
}
}
//先序打印二叉树
void PreOrder(BiTree bt)
{
if(bt)
{
printf("%d ",bt->data);
PreOrder(bt->LChild);
PreOrder(bt->RChild);
}
}
//中序打印二叉树
void InOrder(BiTree bt)
{
if(bt)
{
InOrder(bt->LChild);
printf("%d ",bt->data);
InOrder(bt->RChild);
}
}
//后序打印二叉树
void PostOrder(BiTree bt)
{
if(bt)
{
PostOrder(bt->LChild);
PostOrder(bt->RChild);
printf("%d ",bt->data);
}
}
//先序输出二叉树的叶子结点
void Pre_Order(BiTree bt)
{
if(bt)
{
if(bt->LChild==NULL&&bt->RChild==NULL)
printf("%d ",bt->data);
Pre_Order(bt->LChild);
Pre_Order(bt->RChild);
}
}
//输出叶子结点数目
void LeafCount(BiTree bt)
{
if(bt)
{
LeafCount(bt->LChild);
LeafCount(bt->RChild);
if(bt->LChild==NULL&&bt->RChild==NULL)
Leaf_Count++;
}
}
//输出叶子结点数目
int Leaf(BiTree bt)
{
int Leaf_Count;
if(bt==NULL)
Leaf_Count=0;
else if(bt->LChild==NULL&&bt->RChild==NULL)
Leaf_Count=1;
else
return Leaf(bt->LChild)+Leaf(bt->RChild);
}
int main()
{
BiTree bt;
int Leaf_Count=0;
printf("先序序创建二叉树输入零结束输入\n");
CreateBiTree(&bt);
printf("先序打印二叉树\n");
PreOrder(bt);
printf("\n");
printf("中序打印二叉树\n");
InOrder(bt);
printf("\n");
printf("中序打印二叉树\n");
PostOrder(bt);
printf("\n");
printf("输出二叉树中的叶子结点\n");
Pre_Order(bt);
printf("\n");
printf("后序遍历输出叶子结点数目1.\n");
Leaf_Count=0;
LeafCount(bt);
printf("%d",Leaf_Count);
printf("\n");
printf("后序遍历输出叶子结点数目2.\n");
int num=Leaf(bt);
printf("%d",num);
return 0;
}
为什么会是零,我调试的时候看的也不是0输出就为零了。
[此贴子已经被作者于2017-11-19 14:41编辑过]