程序调试了很长时间,没有错误,但是没办法运行,题目是创建二叉树,前序遍历,求叶子节点数,树深度。输入时以先序遍历序列输入,没有用空格表示。谢谢了。
#include<stdio.h>
#include<stdlib.h>
typedef char TElemType;
typedef struct BiTNode{
TElemType data;
struct BiTNode *lchild,*rchild;
}BiTNode,*BiTree;
BiTree T;
char ch;
int CreatBiTree(BiTree *T)
{
scanf("%c",&ch);
if(ch==' ') T=NULL;
else
{ if(!(T=(BiTree)malloc(sizeof(BiTNode)))) return 0;
(*T)->data=ch;
CreatBiTree(&((*T)->lchild));
CreatBiTree(&((*T)->rchild));
}
return 1;
}
void PreOrder(BiTree T)
{
if(T!=NULL)
{
printf("%c",T->data);
PreOrder(T->lchild);
PreOrder(T->rchild);
}
}
void CountLeaf(BiTree T, int *count)
{
if(T!=NULL)
{ if((!T->lchild) && (!T->rchild)) count++;
CountLeaf(T->lchild,count);
CountLeaf(T->rchild,count);
}
}
int TreeDepth(BiTree T)
{
int depth,depthLeft,depthRight;
if(!T) depth=0;
else
{ depthLeft=TreeDepth(T->lchild);
depthRight=TreeDepth(T->rchild);
depth=1+(depthLeft>depthRight?depthLeft:depthRight);
}
return depth;
}
void main()
{
int count,depth;
int k,l;
printf("以前序遍历的形式输入二叉树:\n");
if(CreatBiTree(&T)) printf("创建成功.\n");
else printf("创建失败.\n");
do
{
printf("执行1前序遍历,2求叶子节点个数,3求深度\n");
scanf("%d",&k);
switch(k)
{
case 1: printf("前序遍历二叉树:\n");
PreOrder(T); break;
case 2: CountLeaf(T, &count); break;
case 3: depth=TreeDepth(T);
}
printf("是否继续执行操作 1是,2否.\n");
scanf("%d",&l);
}while(1);
}