二叉树创建有关问题,为什么输入一个字符后,一直输入‘#’都结束不了
二叉树创建问题,为什么输入一个字符后,一直输入‘#’都结束不了
------解决方案--------------------
楼主的问题已解决!
首先说明您的问题是因为在您输入的一串数据中函数没有过滤掉空格,一楼说的对,之不过她函数用错了
首先您的程序在vc++中输不进去数据了
因为函数把间隔符空格也处理了并没有过滤 请看在您的程序加上标示:
这样程序执行结果为:
1 2 3 # # 4 5 # 6 # # 7 # # #
1@
...1
@
...
2@
...2
@
...
3@
...3
@
...
#@
!!!!!!!!!!!!!!!!!!
@
...
#@
!!!!!!!!!!!!!!!!!!
其他省略
这样楼主是不是能看书来电倪端了??????
是不是空格也处理了? 对吧!
现在在想想 既然空格也处理了那就过滤掉空格不就行了
所以在您scanf后面加上一句 getchar() 就完事了
源代码
#include <stdio.h>
#include <malloc.h>
#define maxsize 100
typedef struct node
{
char data;
struct node *lchild,*rchild;
} *bitree;
bitree create()
{
bitree t;
char ch;
ch=getchar();
if(ch=='#')
t=NULL;
else
{
t=(struct node *)malloc(sizeof(struct node));
t->data=ch;
t->lchild=create();
t->rchild=create();
}
return t;
}
void preorder(bitree t)
{
if(t==NULL)
return ;
else{
printf("%d",t->data);
preorder(t->lchild);
preorder(t->rchild);
}
}
void main()
{
bitree t,p;
t=create();
preorder(t);
printf("...............\n");
}
------解决方案--------------------
楼主的问题已解决!
首先说明您的问题是因为在您输入的一串数据中函数没有过滤掉空格,一楼说的对,之不过她函数用错了
首先您的程序在vc++中输不进去数据了
因为函数把间隔符空格也处理了并没有过滤 请看在您的程序加上标示:
#include <stdio.h>
#include <malloc.h>
#define maxsize 100
typedef struct node
{
char data;
struct node *lchild,*rchild;
} *bitree;
bitree create()
{
bitree t;
char ch;
scanf("%c",&ch);
printf("%c@\n",ch); //输入的数据 以@标示
if(ch == '#')
{
t=NULL;
printf("!!!!!!!!!!!!!!!!!!!\n");//if执行
}
else
{
t=(struct node *)malloc(sizeof(bitree));
t->data=ch;
printf("...%c\n",t->data);//else执行
t->lchild=create();
t->rchild=create();
}
return t;
}
void preorder(bitree t)
{
if(t == NULL)
return;
else
{
printf("%c",t->data);
preorder(t->lchild);
preorder(t->rchild);
}
}
void main()
{
bitree t,p;
t=create();
preorder(t);
printf("...............\n");
}//1 2 3 # # 4 5 # 6 # # 7 # # #
这样程序执行结果为:
1 2 3 # # 4 5 # 6 # # 7 # # #
1@
...1
@
...
2@
...2
@
...
3@
...3
@
...
#@
!!!!!!!!!!!!!!!!!!
@
...
#@
!!!!!!!!!!!!!!!!!!
其他省略
这样楼主是不是能看书来电倪端了??????
是不是空格也处理了? 对吧!
现在在想想 既然空格也处理了那就过滤掉空格不就行了
所以在您scanf后面加上一句 getchar() 就完事了
源代码
#include <stdio.h>
#include <malloc.h>
#define maxsize 100