代码很简单,由于在ubuntu虚拟机下,输入一个字符 ,用getchar会收到字符+回车,不知道怎么消除,所以就简单用strcmp+静态数据i结合来给节点赋值。
至于没有free,这个习惯真不好。but由于程序简单,在程序执行完毕后,系统会给free掉这个进程malloc出来的空间的,简单代码的话对系统没有影响,要是大型系统代码的话,就存在隐患
#include <stdio.h>
#include <malloc.h>
#include <string.h>
typedef struct BiTNode_s{
int data;
struct BiTNode_s *LChild;
struct BiTNode_s *RChild;
}BiTNode;
static int i = 0;
BiTNode* CreateTree()
{
char a[10];
BiTNode *Tree;
scanf("%s",a);
if(!(strcmp("quit",a))){
Tree = NULL;
return Tree;
}
Tree = (BiTNode *)malloc(sizeof(BiTNode));
if(!Tree){
return Tree;
}
Tree->data = i++;
Tree->LChild = CreateTree();
Tree->RChild = CreateTree();
return Tree;
}
int pprintf(BiTNode *Tree)
{
if(Tree == NULL){
//printf("TREE is NULL!\n");
return 0;
}
printf("(");
printf("%d",Tree->data);
if(Tree->LChild) pprintf(Tree->LChild);
if(Tree->RChild) pprintf(Tree->RChild);
printf(")");
return 0;
}
int PreOrder(BiTNode *Tree) //前遍历
{
if(Tree){
printf("%4d",Tree->data);
PreOrder(Tree->LChild);
PreOrder(Tree->RChild);
}
}
int MidOrder(BiTNode *Tree) //中间遍历
{
if(Tree){
PreOrder(Tree->LChild);
printf("%4d\n",Tree->data);
PreOrder(Tree->RChild);
}
}
int main(void)
{
BiTNode *Tree;
Tree = CreateTree();
if(!Tree){
printf("root is null!\n");
return 0;
}
PreOrder(Tree);
printf("\n");
MidOrder(Tree);
pprintf(Tree);
return 0;
}