二叉树建立的问题
我在编写二叉树的建立程序时写的是下面的程序,运行的时候总是出错,但是我真的不知道错在哪里。希望哪位能花时间帮我看一下:
#include <stdio.h>
struct tree *inittree();
void optree(struct tree *T);
struct tree
{
int data;
struct tree *left;
struct tree *right;
};
int main()
{
struct tree *T;
T=inittree();
optree(T);
return 0;
}
struct tree *inittree()
{
struct tree *t;
char ch;
printf( "input\n ");
ch=getchar();
if(ch== '? ') t=NULL;
else
{ t=(struct tree *)malloc(sizeof(struct tree));
t-> data=ch;
t-> left=inittree();
t-> right=inittree();
}
return t;
}
void optree(struct tree *T)
{
if(T)
{
printf( "%d\n ",T-> data);
optree(T-> left);
optree(T-> right);
}
else
{
printf( "There is someting wrong!\n ");
}
}
[解决办法]
修改:如下:
#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
struct tree *inittree();
void optree(struct tree *T);
struct tree
{
int data;
struct tree *left;
struct tree *right;
};
int main()
{
struct tree *T;
T=inittree();
optree(T);
return 0;
}
struct tree *inittree()
{
struct tree *t;
char str[20];
printf( "input\n ");
gets(str);/*是获得字符串,而不是获得字符*/
if(str[0]== '? ') t=NULL;
else
{ t=(struct tree *)malloc(sizeof(struct tree));
t-> data=atoi(str);/*str to int */
t-> left=inittree();
t-> right=inittree();
}
return t;
}
void optree(struct tree *T)
{
if(T)
{
printf( "%d\n ",T-> data);
optree(T-> left);
optree(T-> right);
}
else
{
printf( "There is someting wrong!\n ");
}
}