我感觉我的代码没有问题呀,但是为什么输出不出来?
#include<stdio.h>
#include<malloc.h>
typedef struct Node
{
char data;
struct Node lchild;
struct Node rchild;
}btree;
void preorder_creat(btreet)
{
char x;
x=getchar();
if(x=='.')
{
t=NULL;
}
else
{
t=(btree)malloc(sizeof(btree));
t->data=x;
preorder_creat(t->lchild);
preorder_creat(t->rchild);
}
}
void inorder_putout(btree*t)
{
if(t)
{
inorder_putout(t->lchild);
printf("%c ",t->data);
inorder_putout(t->rchild);
}
}
int main()
{
btree *t;
printf("请输入你想输入的结点值(输入'.'为NULL):\n");
preorder_creat(t);
printf("中序遍历结果为:\n");
inorder_putout(t);
return 0;
}
preorder_creat后的t没有到主函数里
修改如下
#include<stdio.h>
#include<malloc.h>
typedef struct Node
{
char data;
struct Node *lchild;
struct Node *rchild;
} *btree,Node;
btree preorder_creat(btree t)
{
char x;
x=getchar();
if(x=='.')
{
t=NULL;
}
else
{
t=(btree)malloc(sizeof(Node));
t->data=x;
t->lchild=preorder_creat(t->lchild);
t->rchild=preorder_creat(t->rchild);
}
return t;
}
void inorder_putout(btree t)
{
if(t)
{
inorder_putout(t->lchild);
printf("%c ",t->data);
inorder_putout(t->rchild);
}
}
int main()
{
btree t;
printf("请输入你想输入的结点值(输入'.'为NULL):\n");
t=preorder_creat(t);
printf("中序遍历结果为:\n");
inorder_putout(t);
return 0;
}
修改处见注释,供参考:
#include<stdio.h>
#include<malloc.h>
typedef struct Node
{
char data;
struct Node* lchild;
struct Node* rchild;
}btree;
void preorder_creat(btree ** t) //修改
{
char x;
x = getchar();
if (x == '.')
{
(*t) = NULL; //修改
}
else
{
(*t) = (btree*)malloc(sizeof(btree)); //修改
(*t)->data = x;
preorder_creat(&(*t)->lchild); //修改
preorder_creat(&(*t)->rchild); //修改
}
}
void inorder_putout(btree* t)
{
if (t)
{
inorder_putout(t->lchild);
printf("%c ", t->data);
inorder_putout(t->rchild);
}
}
int main()
{
btree* t;
printf("请输入你想输入的结点值(输入'.'为NULL):\n");
preorder_creat(&t); //修改
printf("中序遍历结果为:\n");
inorder_putout(t);
return 0;
}