小弟请高手们帮忙看一下“树的先序输入,先序中序后序输出”错在哪?解决方案
小弟请高手们帮忙看一下“树的先序输入,先序中序后序输出”错在哪??
#include<stdio.h>
#include<malloc.h>
#include<string.h>
typedef char datatype;
typedef struct node
{ datatype data;
struct node *lchild,*rchild;
}binnode;
typedef binnode *bintree;
bintree createbintree(bintree t)//创建树
{
char ch;
if((ch=getchar())=='#')
t=NULL;
else
{
t=(binnode*)malloc(sizeof(binnode));
t->data=ch;
createbintree(t->lchild);
createbintree(t->rchild);
}
}
void preorder(bintree t)//先序遍历
{
if(t)
{
printf("%c",t->data);
preorder(t->lchild);
preorder(t->rchild);
}
}
void inorder(bintree t)//中序遍历
{
if(t)
{
inorder(t->lchild);
printf("%c",t->data);
inorder(t->rchild);
}
}
void postorder(bintree t)//后序遍历
{
if(t)
{
postorder(t->lchild);
postorder(t->rchild);
printf("%c",t->data);
}
}
int main()
{
bintree t;
createbintree(t);
preorder(t);
inorder(t);
postorder(t);
return 0;
}
------解决方案--------------------
在你创立树的时候的问题,需在左右节点都为空的情况下才退出输入,所以对于三个节点的情况,必须输入ab##c##,另外就创建的时候应该通过指针访问,把创建代码改为如下所示,把main中的createbintree(t);改为createbintree(&t)。
bintree createbintree(bintree* t)//创建树
{
char ch;
if((ch=getchar())=='#')
t=NULL;
else
{
*t=(binnode*)malloc(sizeof(binnode));
t->data=ch;
createbintree(&((*t)->lchild)));
createbintree(&((*t)->rchild)));
}
}
在运行时输入ab##c##,按回车后可以看到结果。
#include<stdio.h>
#include<malloc.h>
#include<string.h>
typedef char datatype;
typedef struct node
{ datatype data;
struct node *lchild,*rchild;
}binnode;
typedef binnode *bintree;
bintree createbintree(bintree t)//创建树
{
char ch;
if((ch=getchar())=='#')
t=NULL;
else
{
t=(binnode*)malloc(sizeof(binnode));
t->data=ch;
createbintree(t->lchild);
createbintree(t->rchild);
}
}
void preorder(bintree t)//先序遍历
{
if(t)
{
printf("%c",t->data);
preorder(t->lchild);
preorder(t->rchild);
}
}
void inorder(bintree t)//中序遍历
{
if(t)
{
inorder(t->lchild);
printf("%c",t->data);
inorder(t->rchild);
}
}
void postorder(bintree t)//后序遍历
{
if(t)
{
postorder(t->lchild);
postorder(t->rchild);
printf("%c",t->data);
}
}
int main()
{
bintree t;
createbintree(t);
preorder(t);
inorder(t);
postorder(t);
return 0;
}
------解决方案--------------------
在你创立树的时候的问题,需在左右节点都为空的情况下才退出输入,所以对于三个节点的情况,必须输入ab##c##,另外就创建的时候应该通过指针访问,把创建代码改为如下所示,把main中的createbintree(t);改为createbintree(&t)。
bintree createbintree(bintree* t)//创建树
{
char ch;
if((ch=getchar())=='#')
t=NULL;
else
{
*t=(binnode*)malloc(sizeof(binnode));
t->data=ch;
createbintree(&((*t)->lchild)));
createbintree(&((*t)->rchild)));
}
}
在运行时输入ab##c##,按回车后可以看到结果。