以下是二叉树的建立和先、中、后遍历的程序,其中先序遍历已经实现,但其他两种遍历都有问题,望高手千万指点下!~
#include <stdio.h>
#include <stdlib.h>
typedef struct BiTNode
{
char data;
struct BiTNode *lchild,*rchild;
}BiTree;
BiTree *CreateBiTree()
{
BiTree *T;
char ch;
scanf("%c",&ch);
//fflush(stdin);
/*if(ch=='n')
{
return T;
}*/
if(ch==' ')
{
T=NULL;
}
else
{
if(!(T=(BiTree*)malloc(sizeof(BiTree))))
{
printf("\nError!~");
return T;
}
T->data=ch;
//printf("\nCreate lchild tree:\n");
T->lchild=CreateBiTree();
//printf("\nCreate rchild tree:\n");
T->rchild=CreateBiTree();
}
return T;
}
void PreOrderTraverse(BiTree *T) //先序遍历,
{
if(T!=NULL)
{
printf("%c",T->data);
PreOrderTraverse(T->lchild);
PreOrderTraverse(T->rchild);
}
printf("\n");
}
void MidOrderTraverse(BiTree *T)
{
if(T!=NULL)
{
//printf("%c",T->data);
MidOrderTraverse(T->lchild);
printf("%c",T->data);
MidOrderTraverse(T->rchild);
}
}
void BeOrderTraverse(BiTree *T)
{
if(T!=NULL)
{
BeOrderTraverse(T->lchild);
BeOrderTraverse(T->rchild);
printf("%c",T->data);
}
printf("\n");
}
int main()
{
BiTree *T;
T=(BiTree*)malloc(sizeof(BiTree));
T=CreateBiTree();
PreOrderTraverse(T);
printf("\n");
MidOrderTraverse(T);
printf("\n");
BeOrderTraverse(T);
printf("\n");
return 0;
}