代码如下:
#include <stdio.h>
#include <stdlib.h>
typedef char TElemType ;
typedef struct TNode
{
TElemType data;
struct TNode *lchild , *rchild;
}BiTNode , *BiTree;
int creatTree(BiTree *root) //递归创建二叉树
{
char ch;
scanf("%c" , &ch);
if(ch == '#')
{
(*root) = NULL;
}
else
{
if(!((*root) = (BiTNode *)malloc(sizeof(BiTNode))))
{
printf("malloc error!\n");
return -1;
}
(*root)->data = ch;
creatTree(&((*root)->lchild));
creatTree(&((*root)->rchild));
}
return 0;
}
void preOrderTraverse(BiTree tree) //递归前序遍历
{
if(tree)
{
printf("%c", tree->data);
preOrderTraverse(tree->lchild);
preOrderTraverse(tree->rchild);
}
return ;
}
void inOrderTraverse(BiTree tree) //递归中序遍历
{
if(tree)
{
inOrderTraverse(tree->lchild);
printf("%c", tree->data);
inOrderTraverse(tree->rchild);
}
return ;
}
void lastOrderTraverse(BiTree tree) //递归后序遍历
{
if(tree)
{
lastOrderTraverse(tree->lchild);
lastOrderTraverse(tree->rchild);
printf("%c", tree->data);
}
return ;
}
int main(int argc , char **argv)
{
BiTree tree ;
creatTree(&tree);
printf("\n先序遍历\n");
preOrderTraverse(tree);
printf("\n中序遍历\n");
inOrderTraverse(tree);
printf("\n后序遍历\n");
lastOrderTraverse(tree);
printf("\n");
return 0;
}