数据结构实验
先序创建二叉树,先序遍历,中序遍历,后序遍历。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef char Elemtype;
typedef struct BiTNode
{
Elemtype data;
struct BiTNode *lchild, *rchild;
}BiTNode;
typedef BiTNode * BiTree;
BiTree CreateBiTree()
{
char ch;
BiTree T;
scanf("%c",&ch);
if(ch == '#') T = NULL;
else
{
T = (BiTree )malloc (sizeof(BiTNode ));
if(!T) exit(1);
else
{
T->data = ch;
T->lchild = CreateBiTree();
T->rchild = CreateBiTree();
}
}
return T;
}
void PreOrder(BiTree root)
{
if(root == NULL) return ;
printf("%c", root->data);
PreOrder( root->lchild );
PreOrder( root->rchild );
}
void InOrder(BiTree root)
{
if(root == NULL) return ;
InOrder( root->lchild );
printf("%c", root->data);
InOrder( root->rchild );
}
void PostOrder(BiTree root)
{
if(root == NULL) return ;
PostOrder( root->lchild );
PostOrder( root->rchild );
printf("%c", root->data);
}
int main()
{
printf("1.建立二叉树\n");
printf("2.先序遍历二叉树\n");
printf("3.中序遍历二叉树\n");
printf("4.后序遍历二叉树\n");
printf("请选择:");
BiTree T;
T = (BiTree )malloc(sizeof(BiTNode ));
int a;
while(scanf("%d\n",&a),a)
{
if(a==1)
{
T = CreateBiTree();
printf("建立成功,执行遍历选项:\n");
}
else if(a==2)
{
T = CreateBiTree();
printf("前序遍历:\n");
PreOrder(T);
printf("\n");
}
else if(a==3)
{
T = CreateBiTree();
printf("中序遍历:\n");
InOrder(T);
printf("\n");
}
else if(a==4)
{
T = CreateBiTree();
printf("后序遍历:\n");
PostOrder(T);
printf("\n");
}
}
return 0;
}
/*
测试数据:AB#EG##H##CF###
先序遍历:ABEGHCF
中序遍历:BGHEAFC
后序遍历:GHEBFCA
*/

658

被折叠的 条评论
为什么被折叠?



