问题描述
- 写了一个先序创建二叉链表的程序,但是怎么都不能成功
-
源代码:
#include
#include
#include#define TElemtype char
#define Status int
#define OK 1
#define ERROR 0
typedef struct BiTNode
{
TElemtype data;
struct BiTNode lchild,*rchild;
}BiTNode;
typedef BiTNode BiTree;Status CreateBiTree(BiTree & T)
{
TElemtype temp;
scanf("%c",&temp);
if(temp=='0')
{
T=NULL;
return OK;
}else
{
T=(BiTree)malloc(sizeof(BiTNode));
if(!T)
{
printf("NO MEMORY!
");
return ERROR;
}
T->data=temp;
CreateBiTree(T->lchild);
CreateBiTree(T->rchild);
}
return OK;
}Status PreOrderTraverse(BiTree T)
{
if(T)
{
printf("%c
",T->data);
PreOrderTraverse(T->lchild);
PreOrderTraverse(T->rchild);
}
else return ERROR;
return OK;
}/*Status InOrderTraverse(BiTree *T)
{}*/
int main()
{
printf("Begin to input character:
");
BiTree T;
CreateBiTree(T);
printf("OK
");
PreOrderTraverse(T);getch();
return 0;
}
总是只能不停地输入,无法结束麻烦各位看一下,谢谢!
解决方案
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#define TElemtype char
#define Status int
#define OK 1
#define ERROR 0
typedef struct BiTNode
{
TElemtype data;
struct BiTNode *lchild,*rchild;
}BiTNode;
typedef BiTNode* BiTree;
Status CreateBiTree(BiTree & T)
{
TElemtype temp;
scanf("%c",&temp);
if(temp=='0')
{
T=NULL;
return OK;
}
else
{
T=(BiTree)malloc(sizeof(BiTNode));
if(!T)
{
printf("NO MEMORY!
");
return ERROR;
}
T->data=temp;
T->lchild=NULL; //添加
T->rchild=NULL; //添加
if (CreateBiTree(T->lchild) == OK) return OK; //修改
if (CreateBiTree(T->rchild) == OK) return OK; //修改
}
return OK;
}
Status PreOrderTraverse(BiTree T)
{
if(T)
{
printf("%c
",T->data);
PreOrderTraverse(T->lchild);
PreOrderTraverse(T->rchild);
}
else return ERROR;
return OK;
}
/*Status InOrderTraverse(BiTree *T)
{
}*/
int main()
{
printf("Begin to input character:
");
BiTree T;
CreateBiTree(T);
printf("OK
");
PreOrderTraverse(T);
getch();
return 0;
}
解决方案二:
二叉链表的创建