//数据结构:先序、中序、后序遍历二叉树。输入数据:abd##eg###c#f#h##
#include <stdio.h>
#include <stdlib.h>
//定义数据类型
typedef char Elemtype;
typedef struct tnode
{
Elemtype data;
struct tnode *Lchild; //左孩子
struct tnode *Rchild; //右孩子
}*BiTree;
//创建以t为根的二叉树
void create(BiTree *t)
{
char ch;
scanf("%c",&ch);
if(ch=='#')
{
*t=NULL;
return;
}
else
{
*t=(BiTree)malloc(sizeof(struct tnode));
(*t)->data=ch;
create(&((*t)->Lchild));
create(&((*t)->Rchild));
}
}
//先序遍历二叉树
void PreorderTraverse(BiTree root) /*先序遍历以root为根的二叉树*/
{ if(root!=NULL)
{ printf("%c ",root->data); /*访问根结点*/
PreorderTraverse(root->Lchild); /*先序遍历左子树*/
PreorderTraverse(root->Rchild); /*先序遍历右子树*/
}
}
//中序遍历二叉树
void InorderTraverseBiTree(BiTree root)
{
if(root!=NULL)
{
InorderTraverseBiTree(root->Lchild); //中序遍历左子树
printf("%c ",root->data);
InorderTraverseBiTree(root->Rchild); //中序遍历右子树
}
}
//后序遍历二叉树
void PostorderTraverseBiTree(BiTree root)
{
if(root!=NULL)
{
PostorderTraverseBiTree(root->Lchild); //中序遍历左子树
PostorderTraverseBiTree(root->Rchild); //中序遍历右子树
printf("%c ",root->data);
}
}
void main()
{
BiTree t;
printf("input data: \n"); //输入树的结点:输入数据为:#c#b#egd#f#a#,但是打印是空,不对!
create(&t);
printf("Preorder is: ");
PreorderTraverse(t); //先序遍历以root为根的二叉树
printf("\n");
printf("Inorder is: ");
InorderTraverseBiTree(t); //中序遍历以root为根的二叉树
printf("\n");
printf("Postorder is: ");
PostorderTraverseBiTree(t); //后序遍历以root为根的二叉树
printf("\n");
system("pause");
}
生成二叉树如图:
运行结果: