建立二叉树,并中序遍历

来源:百度知道 编辑:UC知道 时间:2024/06/09 14:07:35
PS1这个程序有问题
想知道在那里
为什么?

#include <stdio.h>
#include <stdlib.h>

typedef struct tnode
{
int value;
struct tnode *lchild;
struct tnode *rchild;
}BTreeNode,*BTree;

BTree createBTree()
{
int value;
BTree t;
scanf("%d",&value);
if (value==0) /* 判断当前子树是否创建完成*/
return NULL;
else
{
t=(BTree)malloc(sizeof(BTreeNode));
t->value=value;
t->lchild=createBTree();
t->rchild=createBTree();
return t;
}
}
void InorderBTree(BTree B)
{
if(B)
{
InorderBTree(B->lchild);
printf("%d\n",B->value);
InorderBTree(B->rchild);
}
}
int main()
{
printf("输入整数,以结尾\n");
BTree B=createBTree();
printf("中序遍历如下:\n");
InorderBTree(B);

其余不变,main函数这样写(VC6.0下调试通过):
int main()
{

struct tnode *B;
printf("输入整数,以结尾\n");
B=createBTree();
printf("中序遍历如下:\n");
InorderBTree(B);
return 0;
}

另外你的main中printf("输入整数,以结尾\n"); 有何作用,有没有scanf函数怎么得到输入值?

帮你看一下,等等
好了,看好了。
你这个程序是个不完整的程序,好多地方都还没有写完。所以程序是不能达到你的目的的。

具体的如下

在你的MAIN函数里面 先printf("输入整数,以结尾\n");
然后就创建树BTree B=createBTree();
你的建树的程序是这样子的

BTree createBTree()
{
int value;
BTree t;
scanf("%d",&value);
if (value==0) /* 判断当前子树是否创建完成*/
return NULL;
else
{
t=(BTree)malloc(sizeof(BTreeNode));
t->value=value;
t->lchild=createBTree();
t->rchild=createBTree();
return t;
}
}

在上面的scanf("%d",&value); 只能接收一个数字,而不能循环的接收多个数字。如果要接收多个数字的话,你需要用一个 while的语句
比如

while (c