假设二叉树为:
a
b c
d e
因为程序中要知道叶子结点(终点),所以要将上面的二叉树变成扩展二叉树 (把叶子结点的孩子补成#, 用作标记), 扩展后就变成了:
a
b c
# d # e
# # # #
那么,在输入的时候,需要输入: ab#d##C#e## (注意,输入后,按enter键即可) ,程序如下:
#include <stdio.h>
#include <malloc.h>
typedef char ElemType;
typedef struct Node
{
ElemType data;
Node *Lchild,*Rchild;
} BiTNode,*BiTree;
BiTree CreateBiTree();//建立二叉树
void PreOrder(BiTree T);//先序
void InOrder(BiTree T);//中序
void PostOrder(BiTree T);//后序
int main(void)
{
BiTree root=CreateBiTree();
printf("先序:\n");
PreOrder(root);//先序
printf("\n");
printf("中序:\n");
InOrder(root);//中序
printf("\n");
printf("后序:\n");
PostOrder(root);//后序
printf("\n");
return 0;
}
BiTree CreateBiTree()//建立二叉树
{
ElemType x;
BiTree T;
scanf("%c",&x);
if(x=='#')
T=NULL;
else
{
T=(BiTree)malloc(sizeof(BiTNode));
T->data=x;
T->Lchild=CreateBiTree();
T->Rchild=CreateBiTree();
}
return T;
}
void PreOrder(BiTree T)//先序
{
if(T!=NULL)
{
printf("%c ",T->data);
PreOrder(T->Lchild);
PreOrder(T->Rchild);
}
}
void InOrder(BiTree T)//中序
{
if(T!=NULL)
{
InOrder(T->Lchild);
printf("%c ",T->data);
InOrder(T->Rchild);
}
}
void PostOrder(BiTree T)//后序
{
if(T!=NULL)
{
PostOrder(T->Lchild);
PostOrder(T->Rchild);
printf("%c ",T->data);
}
}