</pre><pre name="code" class="cpp">#include <stdio.h>
#include <malloc.h>
typedef struct BTNode
{
char data;
struct BTNode *lchild;
struct BTNode *rchild;
}BTNode;
void createTree(BTNode* *T)
{
char ch = getchar();
if(ch=='#')
{
*T=NULL;
return;
}
(*T) = (BTNode*)malloc(sizeof(BTNode));
(*T)->data = ch;
createTree(&(*T)->lchild);
createTree(&(*T)->rchild);
}
void preOrder(BTNode *T)//先序遍历
{
if(T==NULL) return;
printf("%c ", T->data);
if(T->lchild!=NULL)
preOrder(T->lchild);
if(T->rchild != NULL)
preOrder(T->rchild);
}
void inOrder(BTNode *T)//中序遍历
{
if(T==NULL) return;
if(T->lchild!=NULL)
inOrder(T->lchild);
printf("%c ", T->data);
if(T->rchild != NULL)
inOrder(T->rchild);
}
void postOrder(BTNode *T)//后序遍历
{
if(T==NULL) return;
if(T->lchild!=NULL)
postOrder(T->lchild);
if(T->rchild != NULL)
postOrder(T->rchild);
printf("%c ", T->data);
}
int main(int argc, char const *argv[])
{
BTNode *T;
createTree(&T);
puts("PreOrder visit:");
preOrder(T);
putchar('
');
puts("inOrder visit:");
inOrder(T);
putchar('
');
puts("PostOrder visit:");
postOrder(T);
putchar('
');
return 0;
}
/*运行结果:
ABD###C##
PreOrder visit:
A B D C
inOrder visit:
D B A C
PostOrder visit:
D B C A
请按任意键继续. . .*/